Metaclasses in Python

A metaclass is the class of class. While a class defines how an instance of the class behaves, a metaclass defines how a class behaves. A metaclass is most commonly used as a class factory. As we create an instance of the class by calling the class, python creates a new class by calling the metaclass. By defining __init__() and __new__() methods in the metaclass, you can do a lot of extra things (while creating a class) like registering the new class with some registry or replacing the class completely.

Metaclasses in Python

Python allows you to define normal methods on the metaclass which are like class methods, as they can be called on the class without an instance. However, there is a difference between them in that they can’t be called on an instance of the class. Python also allows you to define the normal magic methods such as __add__(), __iter__(), and __getattr__(), etc.