newbie question, what's the difference between built-in functions "__new__" and "__init__"
aleax at aleax.it
Fri Nov 7 09:25:53 CET 2003
> I have studied other's program and found __new__ and __init__ are
> My question is what's the difference between built-in functions
> "__new__" and "__init__". Could anyone help me?
There are no "builtin functions" by these names. There are two methods
in each type that do have these names. I'll assume your reference to
"built-in functions" is a mistake and explain about the methods, by
showing the equivalent Python code that runs them (most are in fact being
used from C, but with semantics just about as below).
When you call any python object XX, e.g.:
x = XX(some, args)
then Python automatically forwards the call to:
x = type(XX).__call__(XX, some, args)
When XX is a typeobject (including a user-coded class, of the "newstyle"
kind), type(XX) is also known as XX's "metaclass". Unless you deliberately
go out of your way to arrange for a custom metaclass, type(XX) is then the
built-in typeobject also known by the name 'type' (slightly confusing...).
So, basically, when you call a normal typeobject XX to instantiate it, what
happens is that method type.__call__ is called. It does basically:
def __call__(cls, *args, **kwds):
result = cls.__new__(cls, *args, **kwds)
if isinstance(result, cls):
type(result).__init__(result, *args, **kwds)
cls is the typeobject you're calling (instantiating). So, in words:
first of all cls.__new__ is called: its job is to return the object
that will be the result of the typeobject call (instantiation). Of
course, normallly it will build and return a NEW object, and normally
an instance of cls, but that is not strictly mandatory.
IF __new__ does return an instance of cls, then initialization is
completed by calling __init__ on the new instance.
So, this is a classic example of "two-phase initialization". The
job of __new__ is providing a new object with the minimum of work
already done on it that just couldn't be done later (e.g. because
a type is immutable); the job of __init__ is completing a new
object's initialization. As a side, somewhat sneaky effect, __new__
can return pre-existing objects (to "recycle" by reinitialziation)
or even instances of completely unrelated types (to let you call a
typeobject as if it were a factory function instead) -- in the latter
case __init__ isn't automatically called.
More information about the Python-list