Multiple ways :
- Way 1
class MyClass:
def __init__(self):
pass
@classmethod
def get(cls):
try:
return cls.instance
except AttributeError:
cls.instance = MyClass()
return cls.instance
- Way 2
this = sys.modules[__name__]
class MyClass:
def __init__(self):
pass
def get_my_singleton():
try:
return this.my_singleton
except AttributeError:
this.my_singleton = MyClass()
return this.my_singleton
More details about this way: https://stackoverflow.com/a/35904211
try:
return this.my_singleton
except AttributeError:
this.my_singleton = MyClass()
return this.my_singleton
More details about this way: https://stackoverflow.com/a/35904211