__new__ static Methods The new class has a __new__ static method, its prototype is object.__new__ (cls[, ...]) The CLS is a class object, and when you call C (*args, **kargs) to create an instance of Class C, the internal invocation of Python is c.__new__ (c, *args, **kargs), and then the return value is instance C of Class C, after confirming that C is an instance of C, Python then calls c.__init__ (C, *args, **kargs) to initialize instance C. So call an instance c = C (2) and actually execute the code: c = c.__new__ (c, 2)
if
isinstance(c, C):
C.
__init__(c) #__init__第一个参数要为实例对象object. __new__ () Creates a new, uninitialized instance. When you override the __new__ method, you can not use the adorner @staticmethod to indicate that it is a static function, and the interpreter will automatically judge this method as a static method. If you need to rebind the c.__new__ method, simply perform c.__new__ = Staticmethod (Yourfunc) outside the class. You can use __new__ to implement Singleton Singleton mode:
classSingleton (object):
_singletons = {}
def__NEW__ (CLS):
if
notCls._singletons.get (CLS): #若还没有任何实例
CLS._SINGLETONS[CLS] = object.__new__ (CLS) #生成一个实例
returnCLS._SINGLETONS[CLS] #返回这个实例运行结果如下: Using the ID () operation, you can see two instances pointing to the same memory address. All subclasses of Singleton also have this attribute, there is only one instance object, if its subclass defines the __init__ () method, then it must be ensured that its __init__ method is safe to make multiple calls to the same instance.
__new__ static method