Last active
July 31, 2018 03:20
-
-
Save tsonglew/5014b1266b1bedabbdf4eeb3f4cf9366 to your computer and use it in GitHub Desktop.
python3 singleton
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
# Method 1. with __new__ magic method | |
class Singleton: | |
def __new__(cls): | |
if not hasattr(cls, 'instance'): | |
cls.instance = super().__new__(cls) | |
return cls.instance | |
class TestSingletonNew(Singleton): | |
pass | |
# Method 2. with decorator | |
def singleton(cls, *args, **kwargs): | |
instances = {} | |
def _singleton(): | |
if cls not in instances: | |
instances[cls] = cls(*args, **kwargs) | |
return instances[cls] | |
return _singleton | |
@singleton | |
class TestSingletonDeco: | |
pass | |
# Run Test | |
tsn1 = TestSingletonNew() | |
tsn2 = TestSingletonNew() | |
assert id(tsn1) == id(tsn2) | |
tsd1 = TestSingletonDeco() | |
tsd2 = TestSingletonDeco() | |
assert id(tsd1) == id(tsd2) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment