-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsingleton.py
46 lines (33 loc) · 827 Bytes
/
singleton.py
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
# class A(object):
# val = None
# # def __init__(self, val):
# # self.set_val = val
# # @property
# # def get_val(self):
# # return self.val
# # @get_val.setter
# # def set_val(self, val):
# # self.__class__.val = val
# def __new__(cls, *arg, **kwargs):
# if cls.val is None:
# cls.val = object.__new__(cls, *arg, **kwargs)
# return cls.val
# def __init__(self, val):
# self.val = val
# a = A(1)
# b = A(1)
# print(id(a), id(b))
def singleton(cls):
_instance = {}
def inner():
if cls not in _instance:
_instance[cls] = cls()
return _instance[cls]
return inner
@singleton
class Test():
def __init__(self):
pass
b1 = Test()
b2 = Test()
print(id(b1) == id(b2))