Characteristics of the __new__ () method:
The __new__ () method is called when the class prepares to instantiate itself.
The __new__ () method is always a static method of the class, even if the static method adorner is not added.
Class A (object): Def __init__ (self): print "Init" def __new__ (Cls,*args, **kwargs): print "new%s"% CLS return object.__new__ (CLS, *args, **kwargs) A ()
Output:
New <class ' __main__. A ' >
Init
Knowledge Points:
New classes that inherit from Object have __new__.
__new__ must have at least one parameter CLS, which represents the class to instantiate, which is automatically provided by the Python interpreter when instantiated.
__new__ must have a return value to return the instantiated instance, which should pay special attention when implementing __new__, can return the instance that the parent class __new__ out, or the __new__ of object directly.
__INIT__ has a parameter, self, which is the instance returned by this __new__, __init__ can perform some other initialization actions based on __new__, __init__ does not need a return value.
If __new__ does not correctly return an instance of the current class CLS , the __init__ will not be called, even if it is an instance of the parent class.
Class A (object): Pass class B (A): def __init__ (self): print "Init" def __new__ (Cls,*args, **kwargs): Print "New%s"%cls return object.__new__ (A, *args, **kwargs) b=b () print type (b)
Output:
New <class ' __main__. B ' >
<class ' __main__. A ' >
Resources:
Http://www.cnblogs.com/ifantastic/p/3175735.html
Http://www.cnblogs.com/tuzkee/p/3540293.html
__new__ and __init__ in Python