__new__ does not call __init__ as described in descrintro.html (WAS: Can __new__ prevent __init__ from being called?)
Steven Bethard
steven.bethard at gmail.com
Tue Feb 15 20:03:14 EST 2005
Felix Wiemann wrote:
> Steven Bethard wrote:
>> http://www.python.org/2.2.3/descrintro.html#__new__
>
[snip]
>
> I'm just seeing that the web page says:
>
> | If you return an existing object, the constructor call will still
> | call its __init__ method. If you return an object of a different
> | class, its __init__ method will be called.
>
> However, the latter doesn't seem to be true, or am I missing
> something?
>
>>>>class A(object):
> ... def __init__(self):
> ... print 'Init of A.'
> ...
>
>>>>instance = A()
> Init of A.
>
>>>>class B(object):
> ... def __new__(self):
> ... return instance
> ... def __init__(self):
> ... print 'Init of B.'
> ...
>
>>>>B() # <--------- A's __init__ is *not* called.
> <__main__.A object at 0x4062424c>
>
>>>>instance = object.__new__(B)
>>>>B() # <--------- B's __init__ is called
> Init of B.
> <__main__.B object at 0x406243ec>
>
> So there seems to be some type-checking in type.__call__.
Yeah, I saw the same thing in playing around with this. Don't know what
to make of it. I wonder if we should file a documentation bug? I can't
find __new__ explained anywhere in the Language Reference. Can
documentation bugs be filed for descrintro.html?
STeVe
More information about the Python-list
mailing list