CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutSign UpSign In
jackfrued

CoCalc provides the best real-time collaborative environment for Jupyter Notebooks, LaTeX documents, and SageMath, scalable from individual users to large groups and classes!

GitHub Repository: jackfrued/Python-100-Days
Path: blob/master/Day16-20/code/example10.py
Views: 729
1
"""
2
装饰类的装饰器 - 单例模式 - 一个类只能创建出唯一的对象
3
上下文语法:
4
__enter__ / __exit__
5
"""
6
import threading
7
8
from functools import wraps
9
10
11
def singleton(cls):
12
"""单例装饰器"""
13
instances = {}
14
lock = threading.Lock()
15
16
@wraps(cls)
17
def wrapper(*args, **kwargs):
18
if cls not in instances:
19
with lock:
20
if cls not in instances:
21
instances[cls] = cls(*args, **kwargs)
22
return instances[cls]
23
24
return wrapper
25
26
27
@singleton
28
class President():
29
30
def __init__(self, name, country):
31
self.name = name
32
self.country = country
33
34
def __str__(self):
35
return f'{self.country}: {self.name}'
36
37
38
def main():
39
print(President.__name__)
40
p1 = President('特朗普', '美国')
41
p2 = President('奥巴马', '美国')
42
print(p1 == p2)
43
print(p1)
44
print(p2)
45
46
47
if __name__ == '__main__':
48
main()
49
50