__new__
Alex Martelli
aleax at mail.comcast.net
Sun Nov 6 11:12:19 EST 2005
Peter Otten <__peter__ at web.de> wrote:
...
> 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)
...
> 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).
Hmmm -- not quite, because in the new-style object model special methods
are taken from the type, NOT from the instance as the latter is saying.
E.g, if you change class B into:
class B(A):
def __init__(self):
print "init B"
def f(): print 'from instance'
self.__init__ = f
you'll see that while b.__init__() would print 'from instance',
instantiating A will not. I think the right correction to the Nutshell
is therefore:
x = C.__new__(C, 23)
if isinstance(x, C): type(x).__init__(x, 23)
and this is how I plan to have it in the 2nd edition.
Alex
More information about the Python-list
mailing list