Skip to content

Commit 8f8e250

Browse files
authored
Chore(signgletone): Add new concept of implement
1 parent 2d88f8d commit 8f8e250

1 file changed

Lines changed: 19 additions & 1 deletion

File tree

src/singleton2.py

Lines changed: 19 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,6 @@
33
Singleton
44
"""
55

6-
76
class Singleton(type):
87
_instance = None
98

@@ -13,6 +12,25 @@ def __call__(cls, *args, **kwargs):
1312
return cls._instance
1413

1514

15+
class Singleton(type):
16+
"""
17+
Singleton metaclass
18+
Based on Python Cookbook 3rd Edition Recipe 9.13
19+
Only one instance of a class can exist. Does not work with __slots__
20+
"""
21+
22+
def __init__(self, *args, **kw):
23+
super(Singleton, self).__init__(*args, **kw)
24+
self.__instance = None
25+
26+
def __call__(self, *args, **kw):
27+
if self.__instance is None:
28+
self.__instance = super(Singleton, self).__call__(*args, **kw)
29+
return self.__instance
30+
31+
32+
33+
1634
class DB(metaclass=Singleton):
1735
pass
1836

0 commit comments

Comments
 (0)