0

I'm trying to create a singleton pattern using metaclass. When i use __new__ method in metaclass it is not getting called when creating the object in it child class and returning the newly created object but when i use __call__ method in metaclass it works fine. I am using python 3. Here is my code:

class meta_class(type):
    _instance = {}
def __new__(cls, *args, **kwargs):
    if cls not in cls._instance:
        inst = cls._instance[cls] = super(meta_class,cls).__new__(cls,*args,**kwargs)
        return inst
    else:
        return cls._instance[cls]

class example(metaclass=meta_class):
    def __init__(self):
        print("instance init")

o = example()
print(o)
p = example()
print(p)

Any help would be more appreciable.

0 Answers0