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)
EDIT: well, I try to say it again (english is not my native language) - with example.
Some functions - I call them
fun(object)
- can useobject.__func__()
to do the job or they use other functions inobject
if there is noobject.__func__()
-
For example
str()
- when you usestr(object)
it callsobject.__str__()
, but if there is noobject.__str__()
then it callsobject.__repr__()
.So you can use
str()
with object which has no__str__()
and still get some result.-
Other example
<
- when you usea < b
it tries to usea.__lt__()
but if there is noa.__lt__()
it tries to usea.__gt__()
(and maybe other functions too)You can remove
__str__
to get different result.You can change
True/False
in__lt__
and you can see that result is changed.Then you can remove
__lt__
and you can changeTrue/False
in__gt__
and you see that result is changed again.According to the spec:
reversed(seq)