Metaclass

type is metaclass which every other class derives. Metaclass defines the creation of the class. However, we can not just manipulate type to customize the creation as this is built-in to python. Python provides the way to pass metaclass while defining class as shown below,

class Meta(type):
    def __new__(cls, name, bases, namespace):
        print("do some customizations on the class")
        _class = super().__new__(cls, name, bases, namespace)
        _class.value = 1
        return _class
 
class A(metaclass=Meta):
    pass
 
A.value # 1

This way, we could add attributes to class A without adding this inside definition of the class itself. It is coming from metaclass Meta. We can use this Meta class for other classes and those will also have attribute value.

We could use __init__ method for adding attributes as shown below,

class Meta(type):
    def __new__(cls, name, bases, namespace):
        print("do some customizations on the class")
        _class = super().__new__(cls, name, bases, namespace)
        _class.value = 1
        return _class
 
    def __init__(cls, name, bases, namespace):
         print(cls)
         cls.extra_value = 12
 
class A(metaclass=Meta):
    pass
 
 
A.value # 1
A.extra_value # 12

__int__ gets the created class from __new__ where we assign extra value.

References

  1. https://realpython.com/python-metaclasses/#custom-metaclasses