Python列表在哪里保存其值?

时间:2016-05-28 00:23:18

标签: python list oop dictionary python-internals

从内省角度看,列表值位于类对象中。 如果list对象是python中的类:

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

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

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

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'}

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

3 个答案:

答案 0 :(得分:3)

这完全取决于实现细节。在cpython中,容器对象仅保存对存储值的引用(指针)。涉及列表内部的任何操作仅操纵指针,而不是对象。

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

>>> 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

你无法在某处找到幕后项目的词典,就像你已经完成了属性一样。列表本身只是一个存储项长度和项目内存位置的数组。

enter image description here

图片来源:here

答案 1 :(得分:2)

不是真的。列表项不存储在列表对象的任何可访问属性下。这只是该语言的低级实现细节。

但是,如果您想要继承list并添加或删除项目,则只需在self上运行列表操作。

In [67]: class TestList(list):
   ....:     def __init__(self, defaultElement):
   ....:         self.append(defaultElement)
   ....:

In [68]: TestList('sample')
Out[68]: ['sample']

...

In [72]: TestList('sample') + ['3']
Out[72]: ['sample', '3']

另请注意,dict()本身没有__dict__

In [73]: dict().__dict__
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-73-58263694ff9c> in <module>()
----> 1 dict().__dict__

AttributeError: 'dict' object has no attribute '__dict__'

您可以在CPython的list()中找到Objects/listobject.c here的源代码实现。

答案 2 :(得分:0)

  

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

是。这是列表本身。例如,如果您定义a

a = ['one', 'two']

然后列表值在a