[Python-Dev] How to suppress instance __dict__?
Guido van Rossum
Sun, 23 Mar 2003 16:15:15 -0500
> It's almost too bad that the distinction between __new__ and __init__
> is there -- as we find we need to legitimize the use of __new__ with
> things like __getnewargs__ it be comes a little less clear which one
> should be used, and when. TIMTOWDI and all that.
__new__ creates a new, initialized object. __init__ sets some values
in an exsting object. __init__ is a regular method and can be called
to reinitialize an existing object (not that I recommend this, but the
mechanism doesn't forbid it). It follows that immutable objects must
be initialized using __new__, since by the time __init__ is called the
object already exists and is immutable.
> In the absence of clear guidelines I'm tempted to suggest that C++ got
> this part right.
Of course you would.
I tend to think that Python's analogon to C++ constructors is __new__,
and that __init__ is a different mechanism (although it can often be
used where you would use a constructor in C++).
> Occasionally we get people who think they want to call overridden
> virtual functions from constructors (I presume the analogous thing
> could be done safely from __init__ but not from __new__)
Whether or not that can be done safely from __init__ depends on the
subclass __init__; it's easy enough to construct examples that don't
work. But yes, for __new__ the situation is more analogous to C++,
except that AFAIK in C++ when you try that you get the base class
virtual function, while in Python you get the overridden method --
which finds an instance that is incompletely initialized.
> but that's pretty rare. I'm interested in gaining insight into the
> Pythonic thinking behind __new__/__init__; I'm sure I don't have the
> complete picture.
__new__ was introduced to allow initializing immutable objects. It
really applies more to types implemented in C than types implemented
in Python. But it is needed so that a Python subclass of an immutable
C base classs can pass arguments of its choice to the C base class's
> Nice. Too bad about 2.2.
Maybe the new pickling could be backported, but I fear that it depends
on some other 2.3 feature that's harder to backport, so I haven't
looked into this.
--Guido van Rossum (home page: http://www.python.org/~guido/)