Returning other instance from __init__
Paul Boddie
paul at boddie.org.uk
Thu Mar 15 07:36:29 EDT 2007
On 15 Mar, 06:21, a... at mac.com (Alex Martelli) wrote:
> Paulo da Silva <psdasil... at esotericaX.ptX> wrote:
> >
> > I would like to implement something like this:
> >
> > class C1:
> > def __init__(self,xxx):
> > if ... :
> > self.foo = foo
> > self.bar = bar
> > else:
> > self=C1.load(xxx)
> >
> > def load(xxx):
> > ...
> > return instance_of_C1
> > load=staticmethod(load)
> >
> > This does not seem correct. How can I do it?
>
> Use __new__ for such purposes, not __init__. (You need to make C1
> newstyle, e.g. inherit from object, to make special method __new__
> work).
Call me a traditionalist, but why wouldn't a factory function be good
enough?
def C1(xxx):
if ...:
return the_real_C1()
else:
return load(xxx)
def load(xxx):
...
return instance_of_C1
Or perhaps seeing more special methods and decorators just puts me in
a grumpy mood. ;-) For me, the power of Python is derived from being
able to do things like making callables "constructors" whilst
providing some illusion that C1 (in this case) is a class.
Paul
More information about the Python-list
mailing list