Metaclass

A metaclass in Python is a class that defines the behavior of other classes that are its instances. In a sense, a metaclass can be thought of as a "class for classes." It sets the rules and constraints for creating and operating classes.

In Python, metaclasses are used to control the process of class creation, modify their attributes and methods, and make various modifications to the behavior of classes and their instances. They provide a powerful tool for metaprogramming, which means programming at the level of creating program code.

class MyMeta(type):
    def __new__(cls, name, bases, attrs):
        # Attribute modifications before class creation
        attrs['custom_attr'] = 42
        return super().__new__(cls, name, bases, attrs)

class MyClass(metaclass=MyMeta):
    pass

obj = MyClass()
print(obj.custom_attr)  # Will output: 42

Comments (0)

Leave a comment