Last active
June 17, 2020 10:18
-
-
Save hnrck/ee0479e46e66f7ae65d33aae558ed2fc to your computer and use it in GitHub Desktop.
Python singleton design pattern
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
from .singleton import Singleton | |
class Example(metaclass=Singleton): | |
""" | |
Example class. | |
""" | |
pass | |
def main(): | |
""" Main function """ | |
onj_1 = Example() | |
obj_2 = Example() | |
assert obj_1 is obj_2 | |
if __name__ == '__main__': | |
main() |
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
""" | |
Singleton design pattern | |
""" | |
class Singleton(type): | |
""" Singleton metaclass """ | |
def __init__(cls, name, bases, attrs, **kwargs): | |
super().__init__(name, bases, attrs, **kwargs) | |
cls._instance = None | |
def __call__(cls, *args, **kwargs): | |
if cls._instance is None: | |
cls._instance = super().__call__(*args, **kwargs) | |
return cls._instance |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment