What is a Python metaclass?
a) A class that defines the behavior of other classes
b) A function used to create classes
c) A built-in type for creating methods
d) A decorator used for class methods
Answer:
a) A class that defines the behavior of other classes
Explanation:
A Python metaclass is a class that defines the behavior of other classes, essentially controlling how classes are created. Metaclasses allow for advanced customization of class creation, including modifying class attributes, adding methods, or enforcing certain design patterns.
class Meta(type):
def __new__(cls, name, bases, attrs):
print(f"Creating class {name}")
return super().__new__(cls, name, bases, attrs)
class MyClass(metaclass=Meta):
pass
# Output: Creating class MyClass
In this example, a metaclass Meta
is defined that prints a message whenever a class is created. The class MyClass
uses this metaclass, so the message is printed when MyClass
is defined.
Metaclasses are a powerful feature in Python, often used in frameworks and libraries to provide dynamic behavior, enforce constraints, or implement domain-specific languages within Python.