I need to implement a singleton class which can be reused in different parts of code. Here is my code
class MyClass(object):
"""sample class to demonstrate singleton pattern"""
def __new__(cls):
if not hasattr(cls, 'instance'):
cls.instance = super(MyClass, cls).__new__(cls)
return cls.instance
def __init__(self):
"""sample init function"""
print("I am init function")
m1=MyClass()
m2=MyClass()
both m1 and m2 point to same memory object however the init function gets called twice. Is there a way I can also limit the init function to one instance ?