Using a base class for a factory function

Scott David Daniels Scott.Daniels at Acm.Org
Wed Jun 15 11:07:50 EDT 2005


Riccardo Galli wrote (approximately):

> I need a class to behave as a factory method for its children so that I could inherit 
 > from it and still use it as a factory.

Several others suggest you probably don't want to do this; I concur.
Separating the factory from the interface (I presume you are doing some
isinstance checking) is probably a good idea.  If, for some reason, you
feel you must implement your original plan, the following code should
outline the trick (look up __new__ and study the code).


     class Interf(object):
         def __new__(klass, kind, *args, **kwargs):
             if kind is None:
                 return object.__new__(klass, *args, **kwargs)
             elif kind == 'a':
                 return Sub1(*args, **kwargs)
             else:
                 assert kind == 'b'
                 return Sub2(*args, **kwargs)
         def __repr__(self):
             return '%s(%s)' % (self.__class__.__name__, ', '.join(
                     '%s=%r' % pair
                     for pair in sorted(vars(self).items())))

     class Sub1(Interf):
         def __new__(klass, *args, **kwargs):
             return Interf.__new__(klass, None, *args, **kwargs)
         def __init__(self, *args, **kwargs):
             self.args = args
             self.kwargs = kwargs

     class Sub2(Interf):
         def __new__(klass, *args, **kwargs):
             return Interf.__new__(klass, None, *args, **kwargs)
         def __init__(self, *args, **kwargs):
             self.xargs = args
             self.xkwargs = kwargs

--Scott David Daniels
Scott.Daniels at Acm.Org



More information about the Python-list mailing list