Returning other instance from __init__

Alex Martelli aleax at mac.com
Thu Mar 15 06:21:13 CET 2007


Paulo da Silva <psdasilvaX 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).

>From __new__ you can return whatever you wish.  However, if you return
an instance of C1, it _will_ be passed to __init__; so, just make sure
__init__ doesn't redo the initialization if passed an
already-initialized self.

E.g.:

class C1(object):
    def __new__(cls, xxx):
        if xxx: return type.__new__(cls, xxx)
        else: return C1.load(xxx)
    @staticmethod
     def load(xxx): return ...whatever...
     def __init__(self, xxx):
         if hasattr(self, 'foo'): return
         self.foo = 'foo'
         self.bar = 'bar'


Alex



More information about the Python-list mailing list