单例
# 案例
# import fcntl
import sys
def singleton(cls):
_instance = {}
def inner():
if cls not in _instance:
_instance[cls] = cls()
return _instance[cls]
return inner
class Singleton(object):
def __init__(self, cls):
self._cls = cls
self._instance = {}
def __call__(self, *args, **kwargs):
if self._cls not in self._instance:
self._instance[self._cls] = self._cls(*args, **kwargs)
return self._instance[self._cls]
class ClassSingle(type):
_instances = {}
def __call__(cls, *args, **kwargs):
if cls not in cls._instances:
cls._instances[cls] = super(ClassSingle, cls).__call__(*args, **kwargs)
return cls._instances[cls]
# class ScriptSingle:
# pid_file = 0
# is_run = False
#
# def __init__(self, filepath):
# self.pid_file = open(filepath, "w")
#
# try:
# fcntl.flock(self.pid_file, fcntl.LOCK_EX | fcntl.LOCK_NB)
# except BaseException:
# self.is_run = True
#
# def is_running(self):
# return self.is_run
if __name__ == '__main__':
@singleton
class A:
pass
a, a1 = A(), A()
print(id(a) == id(a1))
@Singleton
class B:
pass
b, b1 = B(), B()
print(id(b) == id(b1))
class C(metaclass=ClassSingle):
pass
c, c1 = C(), C()
print(id(c) == id(c1))
# s = ScriptSingle('single.pid')
# if s.is_running():
# print('is running!')
# sys.exit(0)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
上次更新: 2023/09/04, 18:39:45