Is there any way to call the init() method of a class only one time. Or how can I disable calling of init() when I create an object from a class?
If you want a singleton, where there is only ever one instance of a class then you can create a decorator like the following as gotten from PEP18:
def singleton(cls):
instances = {}
def getinstance():
if cls not in instances:
instances[cls] = cls()
return instances[cls]
return getinstance
@singleton
class MyClass:
pass
Try it out:
>>> a = MyClass()
>>> b = MyClass()
>>> a == b
True
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With