Junior — Middle
What metaclasses have you used in your projects?
sobes.tech AI
Answer from AI
Metaclasses in Python are classes that create other classes. They allow controlling the class creation process, for example, automatically adding methods or modifying attributes.
In my projects, I have used metaclasses for:
- Automatic registration of classes in a registry (for example, for plugins).
- Validation or modification of class attributes during its creation.
A simple example of a metaclass that adds a hello method to all classes it creates:
class HelloMeta(type):
def __new__(cls, name, bases, dct):
def hello(self):
print(f"Hello from {self.__class__.__name__}!")
dct['hello'] = hello
return super().__new__(cls, name, bases, dct)
class MyClass(metaclass=HelloMeta):
pass
obj = MyClass()
obj.hello() # Outputs: Hello from MyClass!
Metaclasses are useful for creating frameworks and libraries where dynamic class behavior is required.