__new__ static method

Source: Internet
Author: User

__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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.