Junior — Middle
How can a basic metaclass be implemented in Python?
sobes.tech AI
Answer from AI
In Python, a metaclass is a class that creates other classes. To implement a basic metaclass, you need to define a class that inherits from type, and override the __new__ or __init__ method to change the class creation behavior.
Example of a basic metaclass that prints the name of the class being created:
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 output: Creating class MyClass.
Thus, a metaclass allows controlling the class creation process, adding attributes, checking structure, etc.