Metaclasses in Python

A metaclass is the class of a 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 [python]__init__()[/python] and [python]__new__()[/python] 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 [python]__add__()[/python], [python]__iter__()[/python], and [python]__getattr__()[/python], etc.