len() 内置函数是遍历集合以计算其长度,还是访问集合的属性?

Does the len() built-in function iterates through the collection to calculate its length, or does it access a collection's attribute?

Python有很多built-in functionslen()是其中之一。

Return the length (the number of items) of an object. The argument may be a sequence (such as a string, bytes, tuple, list, or range) or a collection (such as a dictionary, set, or frozen set).

如果集合和序列是对象,它们可以拥有一个 length 属性,每次发生变化时该属性都可以更新。访问此属性将是检索集合长度的快速方法。

另一种方法是遍历集合并动态计算项目数。

len()如何计算所述长度?通过迭代或属性访问?一种,none,两种,其他方法?

Python 内置集合将长度缓存在属性中。使用 len() 不会遍历所有元素来计算它们,不会。

将长度保留为一个属性既便宜又易于维护。鉴于 Python 内置集合类型的使用如此广泛, 这样做是不明智的。

例如,

Python 具有长度的内置类型通常构建在 PyObject_VAR_HEAD struct, which includes an ob_size entry. The Py_SIZE macro can then be used to implement the object.__len__ method (e.g. the PySequenceMethods.sq_length slot in the C-API). See the listobject.c implementation for list_length 之上。