__init__ explanation please

Hrvoje Niksic hniksic at xemacs.org
Mon Jan 14 12:53:30 CET 2008

Ben Finney <bignose+hates-spam at benfinney.id.au> writes:

> What one is "in reality" calling is the '__new__' method of the Person
> class. That function, in turn, is creating a new Person instance, and
> calling the '__init__' method of the newly-created instance.  Finally,
> the '__new__' method returns that instance back to the caller.

This is also not entirely correct.  __new__ doesn't call __init__; if
it did, there would be no way to call __new__ without also calling
__init__ (pickle, among other things, does that and needs to do that
to correctly implement its logic).

"In reality" executing Person(...) invokes the __call__ method of
type(Person) (normally the standard metatype called "type") bound to
the Person type object.  This is where the logic to call __new__
followed by __init__ is implemented, in code that does something close
to this:

    obj = mytype.__new__(*args, **kwds)
    if isinstance(obj, mytype):
        mytype.__init__(obj, *args, **kwds)
    return obj

More information about the Python-list mailing list