对于内置类(list、dict、tuple、...),函数len(o)不调用o.__len__(),而是直接调用函数o->tp_as_sequence->sq_length(o)(用 C 实现)(感谢@jfs 的提示)。对于其他类,该函数len(o)调用o.__len__().
一个有趣的观察:
In [137]: l = list(range(10**6))
In [138]: %timeit len(l)
The slowest run took 8.91 times longer than the fastest. This could mean that an intermediate result is being cached.
1000000 loops, best of 3: 314 ns per loop
In [139]: %timeit l.__len__()
The slowest run took 8.42 times longer than the fastest. This could mean that an intermediate result is being cached.
1000000 loops, best of 3: 388 ns per loop
In [152]: class my_len:
...: def __len__(self):
...: return 1
...:
In [153]: a = my_len()
In [154]: %timeit len(a)
The slowest run took 8.22 times longer than the fastest. This could mean that an intermediate result is being cached.
1000000 loops, best of 3: 624 ns per loop
In [155]: %timeit a.__len__()
The slowest run took 8.95 times longer than the fastest. This could mean that an intermediate result is being cached.
1000000 loops, best of 3: 365 ns per loop
__len__
它是一个实现len
操作的魔术方法。与任何其他特殊方法一样,它以特殊方式调用(必须在类本身中定义),也就是说,它len(o)
并不总是等同于o.__len__()
. 更多关于魔术方法的答案。此外,值是
len()
有限的sys.maxsize
:在实践中,长序列有时很有用:
对于内置类(list、dict、tuple、...),函数
len(o)
不调用o.__len__()
,而是直接调用函数o->tp_as_sequence->sq_length(o)
(用 C 实现)(感谢@jfs 的提示)。对于其他类,该函数len(o)
调用o.__len__()
.一个有趣的观察:
obj.__len__()
与 .相比,内置类对象似乎有点慢len(obj)
。如果你
__len__
在自己的类中实现它,那么它会反过来,因为len(obj)
这是一个包装器obj.__len__()
(对于“非内置”类的对象)例子:
更新: 这是一个解释为什么
len(o)
内置类型比 快o.__len__()
的答案:是的,他们返回不同的值。例如 len() 返回列表中元素的数量
并且len方法只能在类中使用并返回其内容以用于列表