Home  >  Article  >  Backend Development  >  How to implement singleton pattern in python

How to implement singleton pattern in python

爱喝马黛茶的安东尼
爱喝马黛茶的安东尼Original
2019-06-22 09:28:412480browse

How to implement singleton pattern in python

How to implement singleton mode in python? Here are seven different methods for you:

##1: staticmethod

The code is as follows:

class Singleton(object):
    instance = None
    def __init__(self):
        raise SyntaxError('can not instance, please use get_instance')
    def get_instance():
        if Singleton.instance is None:
            Singleton.instance = object.__new__(Singleton)
        return Singleton.instance
a = Singleton.get_instance()
b = Singleton.get_instance()
print('a id=', id(a))
print('b id=', id(b))

This method The key point is to throw an exception in __init__, prohibit instantiation through classes, and only obtain instances through the static get_instance function; because it cannot be instantiated through classes, the static get_instance function can be obtained through the parent class object.__new__ Instantiate.

Two: classmethod

Similar to method one, code:

class Singleton(object):
    instance = None
    def __init__(self):
        raise SyntaxError('can not instance, please use get_instance')
    def get_instance(cls):
        if Singleton.instance is None:
            Singleton.instance = object.__new__(Singleton)
        return Singleton.instance
a = Singleton.get_instance()
b = Singleton.get_instance()
print('a id=', id(a))
print('b id=', id(b))

The main point of this method is to throw an exception in __init__ and prohibit passing To instantiate a class, the instance can only be obtained through the static get_instance function; because it cannot be instantiated through a class, the static get_instance function can be instantiated through the parent class object.__new__.

Three: Class attribute method

is similar to method one, code:

class Singleton(object):
    instance = None
    def __init__(self):
        raise SyntaxError('can not instance, please use get_instance')
    def get_instance():
        if Singleton.instance is None:
            Singleton.instance = object.__new__(Singleton)
        return Singleton.instance
a = Singleton.get_instance()
b = Singleton.get_instance()
print(id(a))
print(id(b))

The main point of this method is to throw an exception in __init__, It is prohibited to instantiate through a class, and the instance can only be obtained through the static get_instance function; because it cannot be instantiated through a class, the static get_instance function can be instantiated through the parent class object.__new__.

Four: __new__

Common methods, the code is as follows:

class Singleton(object):
    instance = None
    def __new__(cls, *args, **kw):
        if not cls.instance:
            # cls.instance = object.__new__(cls, *args)
            cls.instance = super(Singleton, cls).__new__(cls, *args, **kw)
        return cls.instance
a = Singleton()
b = Singleton()
print(id(a))
print(id(b))

Related recommendations: "

Python Video Tutorial"

Five: Decorator

The code is as follows:

def Singleton(cls):
    instances = {}
    def getinstance():
        if cls not in instances:
            instances[cls] = cls()
        return instances[cls]
    return getinstance
class MyClass:
    pass
a = MyClass()
b = MyClass()
c = MyClass()
print(id(a))
print(id(b))
print(id(c))

Six: Metaclass

python2 version:

class Singleton(type):
    def __init__(cls, name, bases, dct):
        super(Singleton, cls).__init__(name, bases, dct)
        cls.instance = None
    def __call__(cls, *args):
        if cls.instance is None:
            cls.instance = super(Singleton, cls).__call__(*args)
        return cls.instance
class MyClass(object):
    __metaclass__ = Singleton
a = MyClass()
b = MyClass()
c = MyClass()
print(id(a))
print(id(b))
print(id(c))
print(a is b)
print(a is c)

Or:

class Singleton(type):
    def __new__(cls, name, bases, attrs):
        attrs["_instance"] = None
        return super(Singleton, cls).__new__(cls, name, bases, attrs)
    def __call__(cls, *args, **kwargs):
        if cls._instance is None:
            cls._instance = super(Singleton, cls).__call__(*args, **kwargs)
        return cls._instance
class Foo(object):
    __metaclass__ = Singleton
x = Foo()
y = Foo()
print(id(x))
print(id(y))

python3 version:


class Singleton(type):
    def __new__(cls, name, bases, attrs):
        attrs['instance'] = None
        return super(Singleton, cls).__new__(cls, name, bases, attrs)
    def __call__(cls, *args, **kwargs):
        if cls.instance is None:
            cls.instance = super(Singleton, cls).__call__(*args, **kwargs)
        return cls.instance
class Foo(metaclass=Singleton):
    pass
x = Foo()
y = Foo()
print(id(x))
print(id(y))

Seven: Name coverage

The code is as follows :

class Singleton(object):
    def foo(self):
        print('foo')
    def __call__(self):
        return self
Singleton = Singleton()
Singleton.foo()
a = Singleton()
b = Singleton()
print(id(a))
print(id(b))

The above is the detailed content of How to implement singleton pattern in python. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn