python如何实现单例模式

爱喝马黛茶的安东尼
풀어 주다: 2019-06-22 09:28:41
원래의
2408명이 탐색했습니다.

python如何实现单例模式

python如何实现单例模式?下面给大家带来七种不同的方法:

一:staticmethod

代码如下:

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))
로그인 후 복사

该方法的要点是在__init__抛出异常,禁止通过类来实例化,只能通过静态get_instance函数来获取实例;因为不能通过类来实例化,所以静态get_instance函数中可以通过父类object.__new__来实例化。

二:classmethod

和方法一类似,代码:

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))
로그인 후 복사

该方法的要点是在__init__抛出异常,禁止通过类来实例化,只能通过静态get_instance函数来获取实例;因为不能通过类来实例化,所以静态get_instance函数中可以通过父类object.__new__来实例化。

三:类属性方法

和方法一类似, 代码:

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))
로그인 후 복사

该方法的要点是在__init__抛出异常,禁止通过类来实例化,只能通过静态get_instance函数来获取实例;因为不能通过类来实例化,所以静态get_instance函数中可以通过父类object.__new__来实例化。

四:__new__

常见的方法, 代码如下:

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))
로그인 후 복사

相关推荐:《Python视频教程

五:装饰器

代码如下:

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))
로그인 후 복사

六:元类

python2版:

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)
로그인 후 복사

或者:

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版:

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))
로그인 후 복사

七:名字覆盖

代码如下:

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))
로그인 후 복사

위 내용은 python如何实现单例模式의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

관련 라벨:
원천:php.cn
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
최신 이슈
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!