Created
November 9, 2020 15:58
-
-
Save vladiibine/d9ccd767fea6167cd7e8e078936c33a7 to your computer and use it in GitHub Desktop.
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
# It will be slightly harder to create multiple instances of this class | |
class S: | |
def __init__(self, arg1, arg2): | |
# Dummy method. Used for reflection only | |
pass | |
@classmethod | |
def get_instance(cls, arg1, arg2): | |
# Dummy method. Used for reflection only | |
pass | |
@staticmethod | |
def initialize(): | |
magic_value = object() | |
instances = [None] | |
def __init__(self, arg1, arg2, secret_arg=None): | |
if secret_arg is not magic_value: | |
raise Exception("Told you this is a singleton") | |
self.arg1 = arg1 | |
self.arg2 = arg2 | |
@classmethod | |
def get_instance(cls, arg1, arg2): | |
print("That's the way to do it!") | |
if instances[0]: | |
instances[0] = cls(arg1, arg2, magic_value) | |
return instances[0] | |
return {'__init__': __init__, 'get_instance': get_instance} | |
locals().update(initialize.__func__()) | |
del initialize | |
if __name__ == '__main__': | |
s1 = S.get_instance(1,2) | |
s2 = S.get_instance(3,4) | |
print(s2 is s1) | |
S(2,2) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment