Sobes.tech
Junior — Middle

What special methods of the metaclass are automatically called when creating a new class?

sobes.tech AI

Answer from AI

When creating a new class in Python, the metaclass automatically invokes several special methods, the most important of which are:

  • __new__(cls, name, bases, attrs) — creates a new class object. It is called first and is responsible for creating the class itself.
  • __init__(cls, name, bases, attrs) — initializes the created class, and can be used to set up attributes.
  • __call__(cls, *args, **kwargs) — called when an instance of the class is created (i.e., when the class is called as a function).

The class creation process looks like this:

  1. __new__ of the metaclass is called, which creates the class object.
  2. Then, __init__ of the metaclass is called to initialize the class.

An example of a metaclass overriding these methods:

class Meta(type):
    def __new__(cls, name, bases, attrs):
        print(f"Creating class {name}")
        return super().__new__(cls, name, bases, attrs)

    def __init__(cls, name, bases, attrs):
        print(f"Initializing class {name}")
        super().__init__(name, bases, attrs)

class MyClass(metaclass=Meta):
    pass

When defining MyClass, the following will be printed:

Creating class MyClass
Initializing class MyClass

Thus, these metaclass methods allow controlling the process of creating and configuring new classes.

What special methods of the metaclass are… - sobes.tech