Python列表在哪里保存其值? [英] Where does a Python list hold its values?

查看:124
本文介绍了Python列表在哪里保存其值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

从自省角度来看,列表值位于类对象中. 如果列表对象是python中的类:

From introspection perspective, where list values are located in the class object. If list object is class in python:

>>> a = ['one', 'two']
>>> type(a)
<class 'list'>

所以它存储在类的某个地方,但是在哪里?

So it is stored somewhere in the class, but where?

例如: 如果我们用值定义一个类:

For example: If we define a class with values:

class Test:
    def __init__(self):
        self.test_name = "Do Not"
        self.test_surname = "Know"

很容易找到实例值:

>>> b = Test()
>>> print(a.__dict__)
{'test_surname': 'Know', 'test_name': 'Do not'}

是否有类似的选项可以在列表类对象中达到这些值?

Is there similar option to reach those values in the list class object?

推荐答案

这实际上取决于实现细节.在cpython中,容器对象仅保存对存储值的引用(指针).任何涉及列表内部的操作都只能操作指针,而不能操作对象.

This is really up to the implementation detail. In cpython, the container object only hold references (pointers) to the stored values. Any operation involving the list internals only manipulates the pointers, not the objects.

内存已过度分配,因此总是有一些可用的插槽,这使添加和插入操作更快.分配满后,分配的空间增加了约12.5%.您实际上可以通过附加到列表并在循环中调用sys.getsizeof来看到自己:

Memory is over-allocated so that there are always some free slots available, which makes appends and inserts faster. The space allocated increased by about 12.5% when full. You can actually see that yourself by appending to a list and calling sys.getsizeof in a loop:

>>> import sys
>>> l = []
>>> for i in range(100):
...     print(sys.getsizeof(l)),
...     l.append(None)
...     
72 104 104 104 104 136 136 136 136 200 200 200 200 200 200 200 200 272 272 272 272 272 272 272 272 272 352 352 352 352 352 352 352 352 352 352 440 440 440 440 440 440 440 440 440 440 440 536 536 536 536 536 536 536 536 536 536 536 536 648 648 648 648 648 648 648 648 648 648 648 648 648 648 776 776 776 776 776 776 776 776 776 776 776 776 776 776 776 776 920 920 920 920 920 920 920 920 920 920 920

就像在属性上所做的一样,您无法在某处找到幕后项目的字典.列表本身只是一个数组,用于存储列表的长度和项的存储位置.

You can not find a dict of the items behind the scenes somewhere, like you have done with the attributes. The list itself is merely an array storing it's length and the memory locations of the items.

图片来源:此处

这篇关于Python列表在哪里保存其值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆