Class design issues: multiple constructors

Greg Brunet gregbrunet at NOSPAMsempersoft.com
Thu Aug 7 18:28:32 CEST 2003


Hi Michele

"Michele Simionato" <mis6 at pitt.edu> wrote in message
news:2259b0e2.0308070715.6e9ff32 at posting.google.com...
> If I understand you correctly, this could be done with a metaclass
> redefining the __call__ method and invoking Open or Create depending
> on the number of the arguments:
>
> class MetaTrick(type):
>     def __call__(cls,*args):
>         nargs=len(args)
>         obj=cls.__new__(cls)
>         if nargs==1:
>             obj.Open(*args)
>         elif nargs==2:
>             obj.Create(*args)
>         else:
>             raise 'Wrong number of arguments'
>
> class dbf:
>     __metaclass__=MetaTrick
>     def Create(self, filename, fieldDefs):
>         print filename,fieldDefs
>     def Open(self, filename):
>         print filename
>
> f1 = dbf('customer.dbf')
> f2 = dbf('states.dbf',  [('StateCode', 'C', 2),
>     ('StateName','C',20)])
>
>
> Alternatively, without metaclass, you could redefine the __new__
method
> of the class and use a similar trick.
> HTH,
>


Hmm - I see.  That could work in this instance, but could get more
complex with a different combination of 'constructor' types.  Since
python doesn't seem to handle this overloading for me automatically, I
don't think that it's worth the effort it to manually implement it -
it's likely to be a source of more work & errors down the road.  I'm
kind of leaning to using the 'staticmethod' technique that Alex
mentioned.  Thanks for another view on it - that (metaclasses) gives me
one more technique to use in the future,


-- 
Greg





More information about the Python-list mailing list