Junior — Middle
Have you ever used metaclasses in your projects?
sobes.tech AI
Answer from AI
Metaclasses in Python are classes that create other classes. They allow modifying the behavior of classes during their creation.
In my projects, I have used metaclasses to solve tasks where it is necessary to automatically add methods or attributes to classes, for example, for registering classes in a registry or for creating ORM-like models.
A simple example of a metaclass that adds a method to a class:
class AutoMethodMeta(type):
def __new__(cls, name, bases, attrs):
def hello(self):
return f"Hello from {name}!"
attrs['hello'] = hello
return super().__new__(cls, name, bases, attrs)
class MyClass(metaclass=AutoMethodMeta):
pass
obj = MyClass()
print(obj.hello()) # Outputs: Hello from MyClass!
Using metaclasses requires caution, as they can complicate the understanding of the code.