Returning other instance from __init__

Alex Martelli aleax at mac.com
Thu Mar 15 22:59:10 EDT 2007


Paulo da Silva <psdasilvaX at esotericaX.ptX> wrote:

> Alex Martelli escreveu:
> > Paulo da Silva <psdasilvaX at esotericaX.ptX> wrote:
> ...
> 
> > 
> > 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'
> > 
> 
> 
> Just for a better understanding ...
> Can I do this?
> 
> class C1(object):
>     def __new__(cls, xxx):
>         if xxx:
>               cls.foo='foo'
>               cls.bar='bar'
>               return type.__new__(cls, xxx)
>         else:
>               return C1.load(xxx)
>     @staticmethod
>     def load(xxx): return ...whatever...
>     # OMMIT THE __init__
>     # or
>     def __init__(self, xxx):
>         pass

Yes (omitting the __init__ is better than having it empty), but why do
you want to alter the class object itself, rather than the INSTANCE
you're returning?

I suspect what you really want to do is rather

    if xxx:
        newobj = type.__new__(cls)
        newobj.foo = 'foo'
        newobj.bar = 'bar'
        return newobj
    else ...etc etc...

altering the _instance_ and not the _class_ itself.


Alex



More information about the Python-list mailing list