Classes in Pyth...LOGIN

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)
# 可以直接打印一个类,因为它其实也是一个对象
print(ObjectCreator)
# 可以直接把一个类作为参数传给函数(注意这里是类,是没有实例化的)
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'>
Next Section
submitReset Code
ChapterCourseware