Junior — Middle
Объясните концепцию метакласса и его роль в определении классов в Python
sobes.tech AI
Answer from AI
A metaclass in Python is a class that creates other classes. Simply put, a class is an object, and a metaclass is a "class for classes".
By default, all classes in Python are created using the metaclass type. The metaclass determines how exactly a class is created, what attributes and methods it will have.
The role of a metaclass:
- Manage the process of class creation (for example, automatically adding methods or checking attributes).
- Allow changing the behavior of classes at the stage of their definition.
Example of using a metaclass:
class Meta(type):
def __new__(cls, name, bases, dct):
dct['greet'] = lambda self: f"Hello from {name}!"
return super().__new__(cls, name, bases, dct)
class MyClass(metaclass=Meta):
pass
obj = MyClass()
print(obj.greet()) # Outputs: Hello from MyClass!
Here, the metaclass adds the greet method to all classes that use it.