The structure of a metaclass
A metaclass is like any other class, but it has the ability to alter the behavior of other classes that take it as their metaclass. Understanding the structure of a metaclass helps us create our own customized metaclasses, which can be used further in manipulating new classes. The superclass of a metaclass is the type itself. When we create a class with type
as its superclass and override the __new__
method to manipulate the metadata of a class it returns, then we have created a metaclass. Let’s take a closer look with the help of some simple examples.
The __new__
method takes cls
as its first argument, which is the class itself. The members of the class that has cls
as its first argument can be accessed by the class name and the rest of the arguments as other metadata of the class, as seen here:
class ExampleMetaClass1(type):
def __new__(classitself, *args):
...