Several common implementation methods of Python single mode are described in detail.

Source: Internet
Author: User

Several common implementation methods of Python single mode are described in detail.

This article describes several common implementation methods of Python single mode. We will share this with you for your reference. The details are as follows:

Here python Implementation of the Single Mode, refer to: https://stackoverflow.com/questions/1363839/python-singleton-object-instantiation/1363852#1363852

1. Modify __dict__

class Borg:  _shared_state = {}  def __init__(self):    self.__dict__ = self._shared_stateclass Singleton(Borg):  def __init__(self, name):    super().__init__()    self.name = name  def __str__(self):    return self.namex = Singleton('sausage')print(x)y = Singleton('eggs')print(y)z = Singleton('spam')print(z)print(x)print(y)

Note that this method is not actually implemented in the standalone mode !!

The following methods implement the true standalone mode:

Ii. use metadata

Let's take a look at the metadata description here:

Meta-classes are generally used to create classes.

When executing the class definition, the interpreter must know the correct metadata of the class. The interpreter first looks for class attributes.__metaclass__If this attribute exists, assign this attribute to this class as its metadata. If this attribute is not defined, it looks up__metaclass__. If no__metaclass__Attribute. The Interpreter checks that the name is__metaclass__If it exists, it is used as a metaclass. Otherwise, use the built-in type as the Meta class of this class.

1. inherit type, use__call__

Note:__call__Parameters

class Singleton(type):  _instance = None  def __call__(self, *args, **kw):    if self._instance is None:      self._instance = super().__call__(*args, **kw)    return self._instanceclass MyClass(object):  __metaclass__ = Singletonprint(MyClass())print(MyClass())

2. inherit type, use__new__

Note:__new__Parameters

class Singleton(type):  _instance = None  def __new__(cls, name, bases, dct):    if cls._instance is None:      cls._instance = super().__new__(cls, name, bases, dct)    return cls._instanceclass MyClass(object):  __metaclass__ = Singletonprint(MyClass())print(MyClass())

3. Inheritanceobject, Use__new__

Note:__new__Parameters

class Singleton(object):  _instance = None  def __new__(cls):    if cls._instance is None:      cls._instance = super().__new__(cls)    return cls._instanceclass MyClass(object):  __metaclass__ = Singletonprint(MyClass())print(MyClass())

There is also a clever way to implement the standalone mode.

Usageclassmethod

class Singleton:  _instance = None  @classmethod  def create(cls):    if cls._instance is None:      cls._instance = cls()    return cls._instance  def __init__(self):    self.x = 5    # or whatever you want to dosing = Singleton.create()print(sing.x) # 5sec = Singleton.create()print(sec.x) # 5

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.