Elegant Python-Singleton mode strum

Source: Internet
Author: User

Method One: adorners

With the "adorner will only perform once" feature

1 defSingleton (CLS):2instances = []#Why is this not direct to none, because the intrinsic function cannot access the non-container variables of the external function3     defgetinstance (*args, * *Kwargs):4         if  notinstances:5Instances.append (CLS (*args, * *Kwargs))6         returnInstances[0]7     returngetinstance8 9 @singletonTen classFoo: OneA = 1 A  -F1 =Foo () -F2 =Foo () the PrintID (F1), ID (F2)
Method Two: base class

Use "class variable to be unique to all objects", i.e. cls._instance

1 classSingleton (object):2     def __new__(CLS, *args, * *Kwargs):3         if  notHasattr (CLS,'_instance'):4Cls._instance = object.__new__(CLS, *args, * *Kwargs)5         returncls._instance6 7 classFoo (Singleton):8A = 1
Method Three: Metaclass

Use "class variable to be unique to all objects", i.e. cls._instance

1 classSingleton (type):2     def __call__(CLS, *args, * *Kwargs):3         if  notHasattr (CLS,'_instance'):4Cls._instance = Super (Singleton, CLS).__call__(*args, * *Kwargs)5         returncls._instance6 7 classFoo ():8     __metaclass__= Singleton
Method Four: Borg mode

Use "class variable to be unique to all objects", i.e. __share_state

1 class Foo: 2    __share_state = {}3    def__init__(self):4 Self        . __dict__ = self. __share_state
Method Five: Using Import

Use "module will only be import once"

1 # in the file Mysingleton 2 class Foo (object): 3      Pass 4 5 f = Foo ()

Then in other modules, from Mysingleton import F
Take F directly as a singleton object to use

Transferred from: http://blog.csdn.net/handsomekang/article/details/46672047

Elegant Python-Singleton mode strum

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.