Python review-Singleton mode

Source: Internet
Author: User

#singleton patterns, such as database objects, are instantiated with the same parameters, and there is no need to duplicate objects, wasting memoryclassMysql:__instance=Nonedef __init__(self,host='127.0.0.1', port='3306'): Self.host=host Self.port=Port @classmethoddefSingleton (cls,*args,**Kwargs):if  notCls.__instance: CLS.__instance=cls (*args,**Kwargs)returnCls.__instanceobj1=Mysql () obj2=Mysql ()Print(obj1 isOBJ2)#Falseobj3=Mysql.singleton () Obj4=Mysql.singleton ()Print(obj3 isOBJ4)#True

#application: Custom meta-class for single-instance modeclassMymeta (type):def __init__(self,name,bases,dic):#triggers when class mysql is definedSelf.__instance=None Super ().__init__(name,bases,dic)def __call__(Self, *args, **kwargs):#Mysql (...) Trigger when        if  notSelf.__instance: Self.__instance=object.__new__(self)#Generating ObjectsSelf.__init__(self.)__instance, *args,**kwargs)#Initializing Objects            #The above two steps can be synthesized in the following step            #self.__instance=super (). __call__ (*args,**kwargs)        returnSelf.__instanceclassMysql (metaclass=Mymeta):def __init__(self,host='127.0.0.1', port='3306'): Self.host=host Self.port=portobj1=Mysql () obj2=Mysql ()Print(obj1 isOBJ2)

Python review-Singleton mode

Related Article

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.