Through the above introduction, I finally vaguely brought it to the metaclass. But we still don’t know what metaclasses are.
When we create a class, most of it is to create an instance object of the class. What about metaclasses? Metaclasses are used to create classes. Another way to understand it is: a metaclass is a class of classes.
Through the introduction of the type() function above, we know that classes can be created through the type() function:
MyClass = type('MyClass', (), {})
In fact, the type() function is a metaclass. type() is the metaclass that Python uses behind the scenes to create all classes.
So now we can also guess why the type() function is type instead of Type?
This may be for consistency with str, which is a class used to create string objects, and int is a class used to create integer objects. type is the class that creates the class object. You can see this by inspecting the __class__ attribute. Everything in Python, pay attention, here I mean everything, they are objects. This includes integers, strings, functions, and classes. They are all objects, and they are all created from a class.
# 整形 age = 23 print(age.__class__) # 字符串 name = '两点水' print(name.__class__) # 函数 def fu(): pass print(fu.__class__) # 实例 class eat(object): pass mEat = eat() print(mEat.__class__)
The output results are as follows:
<class 'int'> <class 'str'> <class 'function'> <class '__main__.eat'>
As you can see, everything above, that is, all objects are created through classes, then we may be curious, __class__ of __class__ What could it be? In other words, what are the classes that create these classes?
We can continue to add the following code based on the above code:
print(age.__class__.__class__) print(name.__class__.__class__) print(fu.__class__.__class__) print(mEat.__class__.__class__)
The output results are as follows:
<class 'type'> <class 'type'> <class 'type'> <class 'type'>
Observe carefully, and then clarify, the above output The result is the result of printing the integer age, character creation name, function fu and __class__ of __class__ in the object instance mEat. It can also be said that the class print results of their class. It is found that the printed classes are all type.
As mentioned at the beginning, metaclasses are classes of classes. In other words, a metaclass is a thing responsible for creating a class. You can also understand that the metaclass is responsible for generating classes. And type is the built-in metaclass. That is, Python’s own metaclass.
Next Section