Question regarding __new__

Dustan DustanGroups at gmail.com
Thu Mar 22 18:48:45 EDT 2007


On Mar 22, 10:19 am, Frank Benkstein <frank-pyt... at benkstein.net>
wrote:
> Hi,
>
> the behaviour I always observed when creating instances by calling the
> class A is that '__init__' is always only called when the object
> returned by A.__new__ is an instance of A. This can be observed by the
> following code:
>
> class A(object):
>     def __new__(cls, *args, **kwds):
>         print "A.__new__", args, kwds
>         return object.__new__(B, *args, **kwds)
>     def __init__(cls, *args, **kwds):
>         print "A.__init__", args, kwds
>
> class B(object):
>     def __new__(cls, *args, **kwds):
>         print "B.__new__", args, kwds
>         return object.__new__(cls, *args, **kwds)
>     def __init__(cls, *args, **kwds):
>         print "B.__init__", args, kwds
>
> Interactively A() then gives:
>
> >>> A()
>
> A.__new__ () {}
> <__main__.B object at 0xb7bed0ec>
>
> Yet [1] says: "[...] some rules for __new__: [...] If you return an
> object of a different class, its __init__ method will be called."
>
> Am I missing something? Is this documented somewhere else?

http://docs.python.org/ref/customization.html

> Also it
> would be nice if someone could point me to the function that implements
> this in C. I didn't find anything in object.c or typeobject.c.
>
> Best regards
> Frank Benkstein.
>
> [1]http://www.python.org/download/releases/2.2/descrintro/#__new__
>
> --
> GPG (Mail): 7093 7A43 CC40 463A 5564  599B 88F6 D625 BE63 866F
> GPG (XMPP): 2243 DBBA F234 7C5A 6D71  3983 9F28 4D03 7110 6D51
>
>  signature.asc
> 1KDownload





More information about the Python-list mailing list