[Python] __call__() method in meta-class in python

Discussão em 'Python' iniciado por Stack, Julho 5, 2025.

  1. Stack

    Stack Membro Participativo

    I am having the following piece of code.

    class CustomMetaClass(type):
    def __call__(self, *args, **kwargs):
    print("Custom call method is invoked from custom meta class.")

    class Sample(metaclass=CustomMetaClass):
    def method(self):
    print("Printing from a method")


    I have a custom meta-class and a normal class (Sample). 'Sample' is associated with my custom meta-class.

    Since every thing is an object in Python, whenever the interpretter comes across a class definition, an instance of 'type' is created for the user defined class. This is done via by calling the __call__() of the meta class.

    In the above case, Sample class is associated with my custom metaclass and hence the print statement should have been executed; But it not run actually.

    But when I create instance of Sample ( Sample() ), the print method invoked. As for as I know (from a different stackoverflow question), the same __call__() method in the meta class is used to create instance for the user class (while defining the class) as well of the user defined class (i.e: Sample() )

    Can someone please help where I am wrong here?

    Continue reading...

Compartilhe esta Página