Sobes.tech
Junior — Middle

Explain the role and purpose of metaclasses in Python and how they are used in class definitions.

sobes.tech AI

Answer from AI

Metaclasses in Python are classes for classes. They define how classes are created. Usually, when declaring a class, Python uses the default metaclass type.

The role of metaclasses is to control the class creation process: you can modify attributes, methods, add logic or checks.

Example of usage:

class Meta(type):
    def __new__(cls, name, bases, attrs):
        attrs['custom_attr'] = 'Added by metaclass'
        return super().__new__(cls, name, bases, attrs)

class MyClass(metaclass=Meta):
    pass

print(MyClass.custom_attr)  # Outputs: Added by metaclass

Thus, metaclasses are useful for creating frameworks, ORMs, where you need to automatically modify classes upon their definition.