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 hidden or 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) |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Output
initcalled only once though__init__called twice. So members of the class must be initialized ininit, not__init__.The last two lines of output shows
t1andt2are the same instance.