Why does __init__ not get called?
Steven Bethard
steven.bethard at gmail.com
Thu Aug 11 16:42:53 EDT 2005
Rob Conner wrote:
> By chance... does anyone know, if I wrote a class, and just wanted to
> override __new__ just for the fun of it. What would __new__ look like
> so that it behaves exactly the same as it does any other time.
Simple:
class C(object):
def __new__(cls, *args, **kwargs):
return super(C, cls).__new__(cls, *args, **kwargs)
Basically, you're calling object's __new__ method, which in CPython does
something like mallocing the appropriate amount of memory, setting the
__class__ attribute of the object, etc.
Note that __new__() doesn't call __init__(). Both __new__() and
__init__() are called individually by the metaclass. For new-style
classes, "type" is the metaclass, and it's __call__() method looks
something like:
def __call__(cls, *args, **kwargs):
obj = cls.__new__()
if not isinstance(obj.__class__, cls):
return obj
obj.__class__.__init__(obj, *args, **kwargs)
return obj
(But see Objects/typeobject.c:409 for the full gory details.)
STeVe
More information about the Python-list
mailing list