파이썬에서 싱글턴 패턴을 구현하는 방법은 무엇인가요? 다음은 7가지 방법입니다.
하나: 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))
Two: classmethod
방법 1과 유사, 코드: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))
Three: 클래스 속성 메서드
는 메서드 1과 유사합니다. 코드는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))
Four:__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))
코드는 다음과 같습니다:
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))
Seven: Name Coverage
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 중국어 웹사이트의 기타 관련 기사를 참조하세요!