18 August 2010

Python __init__ and __new__

What is the difference between __init__ and __new__?

Each NEW-style python class has (or inherits from object class) a static method (can be called without creating an object) named __new__. When you call C(*args, **kwds) to create a new instance of class C, Python first calls C.__new__(C, *args, *kwds). Python uses __new__'s return value x as the newly created instance. Then Python calls C.__init__(x, *args, **kwds), but only when x is indeed an instance of C or any of its subclasses.

Thus, the statement x=C(23) is equivalent to:


x = C.__new__(C, 23)
if isinstance(x, C): type(x).__init__(x, 23)


So basically, __new__ is just like new keyword in Java; __new__ and __init__ combine together provide the functionality of an object constructor!

No comments: