-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy path01_singleton.py
61 lines (37 loc) · 966 Bytes
/
01_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
47
48
49
50
51
52
53
54
55
"""
Singleton
- Ensure a class only has one instance, and provide a global point of access to it.
"""
# first method:
from typing import Any
class A:
_instance = None
def __init__(self):
raise RuntimeError('call get_instance() instead')
@classmethod
def get_instance(cls):
if cls._instance is None:
cls._instance = cls.__new__(cls)
return cls._instance
# to test:
try:
one = A()
except:
pass
one = A.get_instance()
two = A.get_instance()
# the ids should be the same
print(id(one))
print(id(two))
# #########################################################
# second method (using meta classes):
class Singleton(type):
_instance = None
def __call__(self, *args: Any, **kwds: Any):
if self._instance is None:
self._instance = super().__call__()
return self._instance
class A(metaclass= Singleton):
pass
one = A()
two = A()