New-style classes have a new special method name, __new__(), that is called on instantiation
before the constructor. It
handles the creation of a new instance.
The .__new__() method is called when
an instance is created.
Method .__new__() is always a static
method (see Section 26.4, “Static methods”),
even if you do not specifically make it a static
method.
A constructor call for
some class has this general form:
C
C(*p, **k)
That is, it can have any number of positional arguments and any number of keyword arguments.
The equivalent call to the .__new__() method will look like this:
def __new__(cls, *p, **k): ...
The first argument must be the class being
created.
cls
The .__new__() method must call the
parent class's .__new__() method to
create the instance.
For example, if your class inherits directly from
object, you must call:
object.__new__(cls)
The value returned by that call is the new instance.
In most cases, the .__new__() method
will return a new instance of , and that class's cls.__init__() will then be called with that
instance as its self argument, and
the positional and keyword arguments and p will be
passed to that constructor as well.
k
>>> class Test(object):
... def __new__(cls, *p, **k):
... inst = object.__new__(cls)
... return inst
... def __init__(self, *p, **k):
... print "p={0} k={1}".format(p, k)
...
>>> t=Test('egg', 'kale', sauce='Bearnaise')
p=('egg', 'kale') k={'sauce': 'Bearnaise'}
However, if the .__new__() method does not return an instance of class , the
constructor method cls.__init__() will
not be called. This allows
the class more control over how new instances are
created and initialized. You can return an
instance of an entirely different class if you
like.