0

I am trying to understand the relation in between python metaclass and class. I was trying to create singleton class and found this code

class SingleTon(type):
    def __call__(self, *args, **kwargs):
        if self._instances is None:
            self._instances = super(SingleTon, self).__call__(*args, **kwargs)
        return self._instances

class Counter:
    __metaclass__ = SingleTon
    _instances = None
    def __init__(self):
        self.count = 1
c = Counter()

my question here is how counter class object is getting created using metaclass. I know metaclass call method gets called whenever we create an object but the confusion is here what this code super(SingleTon, self).__call__(*args, **kwargs) does here. Please explain. It would be very appreciable.

1 Answer 1

1

super will just forward the arguments to type.__call__ which is responsible for the class creation.

It's like calling super in a 'normal' class hierarchy only now, you're calling it in a metaclass. Since SingleTon is a subclass of type, that'll get called. In a class scenario, you'd (normally) forward calls to the base class object.

Sign up to request clarification or add additional context in comments.

4 Comments

So, that means i can use type directly instead of super ??
Yup, try it out! (pass self too, though). That beats the point of using super, though (you're hard-coding names).
Thank you very much jim. Please clear one more thing type(metaclass) method call is responsible for creating instance object. Then how also it creates the class ?
@dheerajsaini That's a loaded question to be honest :-). To keep it as short as I can: type.__call__ handles both cases, depending on what is passed to it either type.__new__/__init__ (or mymetaclass.__new__/__init__ in general) is going to get called for classes or object.__new__/__init__ or (class.__new__/__init__) for instances.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.