__new__

Peter Otten __peter__ at web.de
Sun Nov 6 05:03:18 EST 2005


James Stroud wrote:

> I'm running 2.3.4
> 
> I was reading the documentation for classes & types
>        http://www.python.org/2.2.3/descrintro.html
> And stumbled on this paragraph:
> 
> """
> __new__ must return an object. There's nothing that requires that it
> return a new object that is an instance of its class argument, although
> that is the convention. 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.
> """
> 
> The quote implies that when I call carol, b.__init__ should be called.
> However, this does not seem to be the case (see code below). What am I not
> understanding? Shouldn't the interpreter call b.__init__ when b is
> returned from carol.__new__?

Here's what "Python in a Nutshell" (p84) says:

"""
Each new-style class has a static method named __new__. When you call
C(*args, **kwds) to create a new instance of a new-style class C, Python
invokes C.__new__(C, *args, **kwds). Python uses __new__'s return value x
as the newly created instance. Then, Python calls C.__init__(x, *args,
**kwds), but only when x is indeed an instance of C (otherwise, x's state
is as __new__ had left it). Thus, for a new-style class C, the statement
x=C(23) is equivlent to the following code:

    x = C.__new__(C, 23)
    if isinstance(x, C): C.__init__(x, 23)
"""

If the following code says what I think it does

class A(object):
    def __init__(self):
        print "init A"
    def __new__(cls):
        return b


class B(A):
    def __init__(self):
        print "init B"


b = object.__new__(B)

print "---"
A()              # prints 'init B'
A.__init__(b)    # prints 'init A'
print "---"
b = 42
A()              # prints nothing

the "Nutshell" example should be changed to

    x = C.__new__(C, 23)
    if isinstance(x, C): x.__init__(23)

to comply with the current implementation (I used Python 2.4).

Peter




More information about the Python-list mailing list