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/example18.py
Views: 729
1
"""
2
元 - meta
3
元数据 - 描述数据的数据 - metadata
4
元类 - 描述类的类 - metaclass - 继承自type
5
"""
6
import threading
7
8
9
class SingletonMeta(type):
10
"""自定义元类"""
11
12
def __init__(cls, *args, **kwargs):
13
cls.__instance = None
14
cls.lock = threading.Lock()
15
super().__init__(*args, **kwargs)
16
17
def __call__(cls, *args, **kwargs):
18
if cls.__instance is None:
19
with cls.lock:
20
if cls.__instance is None:
21
cls.__instance = super().__call__(*args, **kwargs)
22
return cls.__instance
23
24
25
class President(metaclass=SingletonMeta):
26
"""总统(单例类)"""
27
28
def __init__(self, name, country):
29
self.name = name
30
self.country = country
31
32
def __str__(self):
33
return f'{self.country}: {self.name}'
34
35
36
def main():
37
"""主函数"""
38
p1 = President('特朗普', '美国')
39
p2 = President('奥巴马', '美国')
40
p3 = President.__call__('克林顿', '美国')
41
print(p1 == p2)
42
print(p1 == p3)
43
print(p1, p2, p3, sep='\n')
44
45
46
if __name__ == '__main__':
47
main()
48
49