Home  >  Article  >  Backend Development  >  What is Python’s object model?

What is Python’s object model?

王林
王林forward
2023-05-18 21:02:431342browse

In object-oriented theory, there are two core concepts: classes and instances. A class can be thought of as a template, and instances are objects created based on this template. In Python, both classes and instances are considered objects, namely class objects (or type objects) and instance objects.

In order to avoid subsequent ambiguities, we divide the objects into three types:

  • Built-in class objects: such as int, str, list, type, object, etc.;

  • Custom class object: a class defined by the class keyword. Of course, we will also refer to it and the built-in class objects above as class objects (or type objects);

  • Instance object: An instance created by a class object (built-in class object or custom class object);

There are the following two relationships between objects :

  • is-kind-of: corresponds to the relationship between subclasses and parent classes in object-oriented theory;

  • is-instance- of: Corresponds to the relationship between instance objects and class objects in object-oriented theory;

Let’s give an example:

class Girl(object):

    def say(self):
        return "古明地觉"

girl = Girl()
print(girl.say())  # 古明地觉

This code includes the above three types Object: object (built-in class object), Girl (custom class object), girl (instance object).

Obviously there is an is-kind-of relationship between Girl and object, that is, Girl is a subclass of object. It is worth mentioning that all classes in Python3 (except object) inherit from object by default. Even if we do not explicitly inherit object here, we will inherit it by default, but for the sake of explanation, we have written it.

In addition to Girl being a subclass of object, we can also see that there is an is-instance-of relationship between girl and Girl, that is, girl is an instance of Girl. Of course, if we go one step further, there is also an is-instance-of relationship between girl and object, and girl is also an instance of object.

class Girl(object):
    pass
    
girl = Girl()
print(issubclass(Girl, object))  # True 
print(type(girl))  # 
print(isinstance(girl, Girl))  # True
print(isinstance(girl, object))  # True

Girl gets a girl instance after being instantiated, so calling type(girl) will return the Girl class object. Girl is an instance object of the Object class because it inherits the Object class. As for the principle of this, we will introduce it slowly.

Python also provides some means to detect these relationships. In addition to the type above, you can also use the __class__ attribute of the object to detect the is-instance-of relationship between an object and which other objects exist.

The __bases__ attribute of the object can detect the is-kind-of relationship between an object and other objects. In addition, Python also provides two functions issubclass and isinstance to verify whether the relationship we expect exists between two objects.

class Girl(object):
    pass 

girl = Girl()
print(girl.__class__)  # 
print(Girl.__class__)  # 
# __class__是查看自己的类型是什么,也就是生成自己的类
# 而在介绍 Python 对象的时候,我们就看到了
# 任何一个对象都至少具备两个东西: 一个是引用计数、一个是类型
# 所以 __class__ 是所有对象都具备的

# __base__只显示直接继承的第一个类
print(Girl.__base__)  # 
# __bases__ 会显示直接继承的所有类,以元组的形式
print(Girl.__bases__)  # (,)

Let’s draw a picture to summarize:

What is Python’s object model?

In addition, we need to pay attention to the type and object inside:

  • type and object have an is-kind-of relationship, because type is a subclass of object;

  • object and type have an is-instance-of relationship, because object is an instance object of type ;

Some people may be curious about why this is the case, and regarding this, I have discussed this in great detail in the article The dispute between type and object. If you are interested, you can click to read it. .

To put it simply, the structure corresponding to type at the bottom layer is PyType_Type, and the structure corresponding to object at the bottom layer is PyBaseObject_Type. When creating object, set the internal ob_type to &PyType_Type; when creating type, set the internal tp_base to &PyBaseObject_Type.

So the definitions of the two are dependent on each other, and they appear at the same time, as we will see later.

In addition, the type of type is type itself, so:

  • The type of instance object is type object, and the type of type object is metaclass;

  • The base classes of all types of objects converge to object;

  • The types of all objects converge to type;

What is Python’s object model?

Therefore, Python can be regarded as implementing the concept of everything as an object to the extreme. It is precisely because of this that Python has such excellent dynamic characteristics.

But it’s not over yet. Let’s take a look at the behavior of the class object Girl. First of all, it supports attribute settings:

class Girl(object):
    pass

print(hasattr(Girl, "name"))  # False
Girl.name = "古明地觉"
print(hasattr(Girl, "name"))  # True
print(Girl.name)  # 古明地觉

In other static languages, once a class is defined, attributes cannot be added. But in our language it is. How does Python implement dynamically adding attributes? Generally we think of dictionary

Just like the global namespace, we guess that the class should also have its own attribute dictionary. When setting attributes in the class, it is equivalent to adding key-value pairs to the dictionary. The same goes for other operations. Also similar to it.

class Girl(object):
    pass

print(Girl.__dict__.get("name", "不存在"))  # 不存在
Girl.name = "古明地觉"
print(Girl.__dict__.get("name"))  # 古明地觉

It is similar to operating global variables, but there is one thing to note: we cannot set attributes directly through the attribute dictionary of the class.

try:
    Girl.__dict__["name"] = "古明地觉"
except Exception as e:
    print(e)  
# 'mappingproxy' object does not support item assignment

虽然叫属性字典,但其实是 mappingproxy 对象,该对象本质上就是对字典进行了一层封装,在字典的基础上移除了增删改操作,也就是只保留了查询功能。要给类增加属性,可以使用直接赋值的方式或调用 setattr 函数。

但在介绍如何篡改虚拟机的时候,我们提到过一个骚操作,可以通过 gc 模块拿到 mappingproxy 对象里的字典。

import gc

class Girl(object):
    pass

gc.get_referents(Girl.__dict__)[0]["name"] = "古明地觉"
print(Girl.name)  # 古明地觉

并且这种做法除了适用于自定义类对象,还适用于内置类对象。但是工作中不要这么做,知道有这么个操作就行。

除了设置属性之外,我们还可以设置函数。

class Girl(object):
    pass

Girl.info = lambda name: f"我是{name}"
print(Girl.info("古明地觉"))  # 我是古明地觉

# 如果实例调用的话,会和我们想象的不太一样
# 因为实例调用的话会将函数包装成方法
try:
    Girl().info("古明地觉")
except TypeError as e:
    print(e) 
"""
() takes 1 positional argument but 2 were given
"""    

# 实例在调用的时候会将自身也作为参数传进去
# 所以第一个参数 name 实际上接收的是 Girl 的实例对象
# 只不过第一个参数按照规范来讲应该叫做self
# 但即便你起别的名字也是无所谓的
print(Girl().info())  
"""
我是<__main__.Girl object at 0x000001920BB88760>
"""

所以我们可以有两种做法:

# 将其包装成一个静态方法
# 这样类和实例都可以调用
Girl.info = staticmethod(lambda name: f"我是{name}")
print(Girl.info("古明地觉"))  # 我是古明地觉
print(Girl().info("古明地觉"))  # 我是古明地觉

# 如果是给实例用的,那么带上一个 self 参数即可
Girl.info = lambda self, name: f"我是{name}"
print(Girl().info("古明地觉"))  # 我是古明地觉

此外我们还可以通过 type 来动态地往类里面进行属性的增加、修改和删除。

class Girl(object):

    def say(self):
        pass

print(hasattr(Girl, "say"))  # True
# delattr(Girl, "say") 与之等价
type.__delattr__(Girl, "say")
print(hasattr(Girl, "say"))  # False
# 我们设置一个属性吧
# 等价于 Girl.name = "古明地觉"
setattr(Girl, "name", "古明地觉")
print(Girl.name)  # 古明地觉

事实上调用 getattr、setattr、delattr 等价于调用其类型对象的__getattr__、__setattr__、__delattr__。

所以,一个对象支持哪些行为,取决于其类型对象定义了哪些操作。并且通过对象的类型对象,可以动态地给该对象进行属性的设置。Python 所有类型对象的类型对象都是 type,通过 type 我们便可以控制类的生成过程,即便类已经创建完毕了,也依旧可以进行属性设置。

但是注意:type 可以操作的类只能是通过 class 定义的动态类,而像 int、list、dict 等静态类,它们是在源码中静态定义好的,只不过类型设置成了 type。一言以蔽之,type 虽然是所有类对象的类对象,但 type 只能对动态类进行属性上的修改,不能修改静态类。

try:
    int.name = "古明地觉"
except Exception as e:
    print(e)
"""
can't set attributes of built-in/extension type 'int'
"""

try:
    setattr(int, "ping", "pong")
except Exception as e:
    print(e)
"""
can't set attributes of built-in/extension type 'int'     
"""

内置类和扩展类的属性无法被设置,这是由于内置类在解释器启动后就已被初始化。可以通过报错信息观察到这点。我们所说的扩展类,是指我们使用 Python/C API 编写的扩展模块中的类,其与内置类具有相同的地位。

因此内置类和使用 class 定义的类本质上是一样的,都是 PyTypeObject 对象,它们的类型在 Python 里面都是 type。不同的是,内置类在底层是以静态初始化方式实现的,因此我们无法通过动态设置属性的方式来操作它们(除非使用 gc 模块)。

但是为什么不可以对内置类和扩展类进行属性设置呢?首先我们要知道 Python 的动态特性是虚拟机赐予的,而虚拟机的工作就是将 PyCodeObject 对象翻译成 C 的代码进行执行,所以 Python 的动态特性就是在这一步发生的。

同理,扩展类和内置类在解释器启动后都已经被静态初始化,并直接指向 C 一级的数据结构。它们与解释执行绕开了相应过程,因此无法在其上动态添加属性。

不光内置的类本身,还有它的实例对象也是如此。

a = 123
print(hasattr(a, "__dict__"))  # False

我们发现它甚至连自己的属性字典都没有,因为解释器对于内置类对象的实例对象,其内部的属性和方法是已知的。由于底层代码已被固定且不允许修改,因此在实现虚拟机时无需创建属性字典,以节省内存。

The above is the detailed content of What is Python’s object model?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete