The application of a singleton pattern in Python

Source: Internet
Author: User

1 use __new__Method

Class Singleton (object):
Def __new__ (CLS, *args, **kw):
If not hasattr (CLS, ' _instance '):
Orig = Super (Singleton, CLS)
Cls._instance = orig.__new__ (CLS, *args, **KW)
Return cls._instance

Class MyClass (Singleton):
A = 1

2 Shared properties

When you create an instance, you point all instances to the __dict__ same dictionary, so that they have the same properties and methods.

class Borg(object): _state = {}     def __new__ (cls,< Span class= "crayon-h" > *args, **kw) Span class= "Crayon-o" >:         ob = super (borg, cls) . __new__ (cls, Span class= "Crayon-o" >*args, **kw) ob. __dict__ = cls. _state return ob class MyClass2(Borg): a = 1 3 Adorner version

Def Singleton (CLS, *args, **kw):
instances = {}
Def getinstance ():
If CLS not in instances:
INSTANCES[CLS] = CLS (*args, **KW)
return INSTANCES[CLS]
Return getinstance

@singleton
Class MyClass:
...

4:import version

As a Python module, it's a natural, single-case pattern.

# mysingleton.py
Class My_singleton (object):
def foo (self):
Pass

My_singleton = My_singleton ()

# to use
From Mysingleton import My_singleton

My_singleton.foo ()

The application of a singleton pattern in Python

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.