Classes in Python are also objects
Before understanding metaclasses, we first further understand classes in Python. In most programming languages, a class is a set of code segments used to describe how to generate an object. This is the same in Python.
class ObjectCreator(object): pass mObject = ObjectCreator() print(mObject)
Output result:
<__main__.ObjectCreator object at 0x00000000023EE048>
However, classes in Python are different from most programming languages. In Python, a class can be understood as an object. Yes, there is no mistake here, it is the object.
why?
Because as long as the keyword class is used, the Python interpreter will create an object during execution.
For example:
class ObjectCreator(object): pass
When the program runs this code, an object will be created in the memory, and the name is ObjectCreator. This object (class) itself has the ability to create objects (class instances), and that's why it is a class. However, its essence is still an object, so we can do the following operations on it:
class ObjectCreator(object): pass def echo(ob): print(ob) mObject = ObjectCreator() print(mObject) # 可以直接打印一個類,因?yàn)樗鋵?shí)也是一個對象 print(ObjectCreator) # 可以直接把一個類作為參數(shù)傳給函數(shù)(注意這里是類,是沒有實(shí)例化的) echo(ObjectCreator) # 也可以直接把類賦值給一個變量 objectCreator = ObjectCreator print(objectCreator)
The output result is as follows:
<__main__.ObjectCreator object at 0x000000000240E358> <class '__main__.ObjectCreator'> <class '__main__.ObjectCreator'> <class '__main__.ObjectCreator'>