Question regarding __new__

Frank Benkstein frank-python at benkstein.net
Thu Mar 22 12:19:52 EDT 2007


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? 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
-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 196 bytes
Desc: not available
URL: <http://mail.python.org/pipermail/python-list/attachments/20070322/f0a67b71/attachment.sig>


More information about the Python-list mailing list