Sobes.tech
Junior — Middle

How does the metaclass mechanism work in Python?

sobes.tech AI

Answer from AI

The mechanism of metaclasses in Python allows controlling the creation of classes. A metaclass is a class that creates other classes.

When you define a class, Python calls the metaclass to create that class. By default, the metaclass is type.

Example of using a metaclass:

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

class MyClass(metaclass=Meta):
    pass

# When defining MyClass, it will print: Creating class MyClass

Metaclasses are useful for modifying classes during their creation, for example, for registering classes, checking attributes, or automatically adding methods.