面试题:装饰器实现单例
[Python] 纯文本查看 复制代码 def single(cls):
instance = dict()
def wrapped_cls(*args, **kwargs):
if cls not in instance:
instance[cls] = cls(*args, **kwargs)
return cls
return wrapped_cls
@single
class MyClass(object):
pass
if __name__ == '__main__':
t1 = MyClass()
t2 = MyClass()
print(id(t1))
print(id(t2))
|