我在这里遇到了peternorvig的单例类实现http://norvig.com/python-iaq.html
def singleton(object, instantiated=[]):
"Raise an exception if an object of this class has been instantiated before."
assert object.__class__ not in instantiated, \
"%s is a Singleton class but is already instantiated" % object.__class__
instantiated.append(object.__class__)
class YourClass:
"A singleton class to do something ..."
def __init__(self, args):
singleton(self)
...
我的问题是,如果我们在第二次创建两个YourClass实例,为什么instantiated
不是空列表?instantiated
的范围是什么
谢谢你
从docs:
instantiated
的值绑定到函数定义,并且在定义singleton
时只初始化一次因此,每次调用该函数时,只有一个相同列表的副本:
同:
如果希望
instantiated
在后续函数调用之间被隔离,则应将其定义为local variable
:相关问题 更多 >
编程相关推荐