def singleton(cls):
... instances = {}
... def getinstance(*args, **kw):
... if cls not in instances:
... instances[cls] = cls(*args, **kw)
... return instances[cls]
... return getinstance
...
... @singleton
... class MyClass:
... pass
...
c = MyClass()
c1 = MyClass()
type(c)
<class '__main__.MyClass'>
type(c1)
<class '__main__.MyClass'>
id(c)
4358766264
id(c1)
4358766264
singleton
中instances
已经超出了原函数的作用域,在getinstance
函数中还能使用,这是闭包的特性。
instances
从字典类型改成None
,会出现报错在 local 变量中不到instances
!def singleton1(cls):
... instances = None
... def getinstance(*args, **kw):
... if instances is None:
... instances = cls(*args, **kw)
... return instances
... return getinstance
...
... @singleton1
... class MyClass1:
... pass
...
mc1 = MyClass1()
Traceback (most recent call last):
File "<input>", line 1, in <module>
File "<input>", line 4, in getinstance
UnboundLocalError: local variable 'instances' referenced before assignment
这是为什么?希望大佬说说