def singleton(cls):
instances = {}
def getInstance():
if cls not in instances:
instances[cls] = cls()
return instances[cls]
return getInstance
@singleton
class A(object):pass
@singleton
class B(object):pass
a1=A()
a2=A()
b1=B()
b2=B()
print id(a1),id(a2)
print id(b1),id(b2)
结果
(<__main__.A at 0x7f0921e03f50>, <__main__.A at 0x7f0921e03f50>)
(<__main__.B instance at 0x7f0921dbe440>, <__main__.B instance at 0x7f0921dbe440>)
如上, 怎么理解 singleton中的变量 instances ?
instances 在运行中如何存贮实例呢? 请大牛指教
忽然笑
相关分类