为什么Python中的元组可以反转但没有__reversed__?

在讨论this answer时,我们意识到元组没有__reversed__方法.我的猜测是创建迭代器需要改变元组.然而,元组在逆转时发挥得很好.为什么不能将用于反转的方法用于__reversed__?

>>> foo = range(3)
>>> foo
[0, 1, 2]
>>> list(foo.__reversed__())
[2, 1, 0]
>>> foo
[0, 1, 2]
>>> bar = (0, 1, 2)
>>> list(bar.__reversed__())
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'tuple' object has no attribute '__reversed__'
>>> reversed(bar)
<reversed object at 0x10603b310>
>>> tuple(reversed(bar))
(2, 1, 0)

解决方法:

根据spec

逆转(SEQ)

Return a reverse iterator. seq must be an object which has a
reversed() method or supports the sequence protocol (the __len__() method and the __getitem__() method with integer arguments starting at
0).

上一篇:js对select动态添加和删除OPTION


下一篇:c# – 对元组列表进行排序时的默认行为是什么?