Last active
September 17, 2019 15:43
-
-
Save pn11/bf7e0ebf80f8a7293e77cc1e58fe1c14 to your computer and use it in GitHub Desktop.
Singleton in Python3
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import threading | |
class ThreadingSingleton: | |
_instance = None | |
_lock = threading.Lock() | |
def __init__(self): | |
print('__init__') | |
def __new__(cls): | |
with cls._lock: | |
if cls._instance is None: | |
cls._instance = super().__new__(cls) | |
cls._instance.init() | |
return cls._instance | |
def init(self): | |
self.test = False | |
print('init') | |
if __name__ == "__main__": | |
t1 = ThreadingSingleton() | |
t2 = ThreadingSingleton() | |
print(t1.test) | |
print(t2) | |
print(t1) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Output
init
called only once though__init__
called twice. So members of the class must be initialized ininit
, not__init__
.The last two lines of output shows
t1
andt2
are the same instance.