1.__new__ (CLS, *args, **kwargs) is invoked when an object is created, returning an instance of the current object; Note: The first argument here is the CLS, the class itself.
2.__init__ (self, *args, **kwargs) is invoked after the object is created, with some initialization of the instance of the current object, no return value, that is, after the call to __new__, based on the returned instance; Note that the first argument here is self, the object itself. Notice the difference with new "
3.__call__ (self, *args, **kwargs) If the class implements this method, it is equivalent to using this type of object as a function, equivalent to overloading the bracket operator
See the specific example:
Copy Code code as follows:
Class O (object):
def __init__ (self, *args, **kwargs):
Print "Init"
Super (O, self). __init__ (*args, **kwargs)
Def __new__ (CLS, *args, **kwargs):
Print "New", CLS
Return Super (O, CLS). __new__ (CLS, *args, **kwargs)
def __call__ (self, *args, **kwargs):
Print "Call"
oo = O ()
Print "________"
OO ()
The print out is:
Copy Code code as follows:
For example: Python Singleton (single case mode) implementation, then we are not just overloading some __new__ methods on it
Copy Code code as follows:
Class Singleton1 (object):
"" "Overload New Method" ""
Def __new__ (CLS, *args, **kwargs):
If not ' _instance ' in VARs (CLS):
Cls._instance = Super (Singleton1, CLS). __new__ (CLS, *args, **kwargs)
Return cls._instance
Can you overload the __init__ method? Obviously not, because __init__ before the __new__ method, this time has generated an object, no way to implement a single case pattern