标签:pre app return main war rap contents closure pass
def singleton(cls):
instances = {}
def wrapper(*args, **kwargs):
if cls not in instances:
instances[cls] = cls(*args, **kwargs)
return instances[cls]
return wrapper
@singleton
class Foo:
pass
f1 = Foo()
f2 = Foo()
print(dir(Foo))
# (<cell at 0x7f9ad3ede040: type object at 0x55929df326a0>, <cell at 0x7f9ad3e9e580: dict object at 0x7f9ad3ee8140>)
print(Foo.__closure__)
print(Foo.__closure__[1].cell_contents) # {<class ‘__main__.Foo‘>: <__main__.Foo object at 0x7f1533a19be0>}
Python - 装饰器装饰class,访问闭包中的自由变量
标签:pre app return main war rap contents closure pass
原文地址:https://www.cnblogs.com/allen2333/p/12628425.html