本文介绍了为什么Python中的元组可以反转但没有__reversed__?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在讨论时,我们意识到元组没有 __颠倒__ 方法。我的猜测是创建迭代器需要改变元组。然而,元组在反转时可以正常运行。为什么反转的方法不能用于 __ reverse __

In discussion of this answer we realized that tuples do not have a __reversed__ method. My guess was that creating the iterator would require mutating the tuple. And yet tuples play fine with reversed. Why can't the approach used for reversed be made to work for __reversed__ as well?

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


推荐答案

根据:

反转(seq)

这篇关于为什么Python中的元组可以反转但没有__reversed__?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-21 13:53