【发布时间】:2012-06-21 16:53:18
【问题描述】:
In this answer 一个单例装饰器就是这样演示的
def singleton(cls):
instances = {}
def getinstance():
print len(instances)
if cls not in instances:
instances[cls] = cls()
return instances[cls]
return getinstance
但是instances 对每个被装饰的类都是“本地的”,所以我试图提高效率并使用
def BAD_singleton(cls):
instances = None
def getinstance():
if instances is None:
instances = cls()
return instances
return getinstance
@BAD_singleton
class MyTest(object):
def __init__(self):
print 'test'
但是,这会产生错误
UnboundLocalError: local variable 'instances' referenced before assignment
当m = MyTest() 被调用时
我想我知道这不应该工作(因为分配给实例将是本地的并且在调用之间丢失),但我不明白为什么我会收到这个错误。
【问题讨论】:
-
一个更完整的
@singleton。 -
@ehemient 谢谢。总的来说,这是一个非常有用的页面。