标签:init val object test 一个 实现 self == rgs
单例模式: 顾名思义,一个类,在整个项目的运行周期内只有一个实例
def singleton(cls,*args,**kwargs):
instance = {}
def _singleton():
if cls not in instance:
instance[cls] = cls(*args,**kwargs)
return instance[cls]
return _singleton
@singleton
class test_singleton(object):
def __init__(self):
self.sum = 0
def add(self):
self.num = 100
cls1 = test_singleton()
cls2 = test_singleton()
print(id(cls1)==id(cls2))
利用__new__实现单例子
class A(object):
__instance = None
def __new__(cls, *args, **kwargs):
if cls.__instance is None:
cls.__instance = object.__new__(cls,*args,**kwargs)
return cls.__instance
def __init__(self):
self.value = 3
a = A()
a.value = 2
print(a.value)
b = A()
print(a is b)
print(a.value)
print(b.value)
标签:init val object test 一个 实现 self == rgs
原文地址:https://www.cnblogs.com/djongsir/p/9986752.html