Hacking with __new__

Sandra-24 sandravandale at yahoo.com
Tue Jul 24 13:58:18 EDT 2007


On Jul 24, 5:20 am, Bruno Desthuilliers <bruno.
42.desthuilli... at wtf.websiteburo.oops.com> wrote:
> IIRC, __new__ is supposed to return the newly created object - which you
> are not doing here.
>
> class Bar(Foo):
>      def __new__(cls, a, b, c, *args):
>          print 'Bar.__new__', len(args)
>          if not args:
>              cls = Zoo
>          obj = super(Bar, cls).__new__(cls, a, b, c, *args)
>          if not args:
>              obj.__init__(a, b, c, 7)
>          return obj

Thanks guys, but you are right Bruno, you have to return the newly
created object or you get:

>>> b = Bar(1,2,3)
Bar.__new__ 0
Foo.__new__ 3
Zoo.__init__ 4
Foo.__init__ 3
>>> b is None
True

However, if you return the object you get:

>>> b = Bar(1, 2, 3)
Bar.__new__ 0
Foo.__new__ 3
Zoo.__init__ 4
Foo.__init__ 3
Traceback (most recent call last):
  File "<input>", line 1, in <module>
TypeError: __init__() takes exactly 5 arguments (4 given)

Which is the same blasted error, because it seems to want to call init
on the returned object and it's calling it with 4 args :( Is there any
way around that?

Thanks,
-Sandra





More information about the Python-list mailing list