Metaclass in python refers to the object used to create a class. The type() function in python is actually a metaclass. The type() function is used to create metaclasses of all classes. If you want to create a custom metaclass, you must also inherit from type.
In Python, classes are also objects. When we use the class keyword to create a class, the Python interpreter just scans the syntax of the class definition. Then call the type() function to create the class. So do you know what creates a class? In fact, he is a metaclass.
What is a metaclass?
Metaclasses are actually objects used to create classes.
To help us understand, we can think of it this way, We create a class to create an instance of the class. Similarly, we create a metaclass to create a class.
Metaclass is the class (instance) of the class, like the following:
Metaclass() = class class() = object # object==>实例
Understanding what a metaclass is, let’s take a look at type ()function.
In fact, type is a metaclass, and type is the metaclass we use to create all classes. (If we want to create our own metaclass, we must also inherit from type)
How metaclasses work:
Let’s take a look The following example
class ReedSunMetaclass(type): pass class Foo(object, metaclass = ReedSunMetaclass): pass class Bar(Foo): pass
First, we created a metaclass ReedSunMetaclass
(Note! According to the default habit, the class name of the metaclass always ends with Metaclass, so that clearly indicates that this is a metaclass).
Then, we created a Foo class using the metaclass ReedSunMetaclass.
(At the same time, the attribute __metaclass__ of the Foo class becomes ReedSunMetaclass).
Finally, we created a subclass Bar that inherits from Foo.
Let’s try to understand how these steps are performed inside python:
For the parent class Foo, Python will look for _ in the definition of the class. _metaclass__ attribute, if found, Python will use it to create class Foo, if not found, it will use the built-in type to create this class. Apparently, it was found.
For the subclass Bar, Python will first search for the __metaclass__ attribute in the subclass. If found, Python will use it to create the class Bar. If not found, it will search again from the parent class. Until type. Apparently, it's found in the parent class.
We can see one benefit of using metaclasses, that is, it allows subclasses to implicitly inherit something.
The above is the detailed content of What is a metaclass in Python. For more information, please follow other related articles on the PHP Chinese website!