Why do tuples in Python work the other way around but don't have __reversed__?

In the discussion of this answer, we realized that tuples do not have the __reversed__ method. I assumed that creating a iterator would require a tuple mutation. Still, tuples work great with reversed . Why can't I use the reversed method to work with __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) 
+4
source share
2 answers

According to spec :

reverse (cl)

Return the reverse iterator. seq must be an object that has a modified () method or supports the sequence protocol (the __len __ () method and the __getitem __ () method with integer arguments starting at 0).

+9
source

EDIT: Well, I'm trying to repeat this (English is not my native language) - with an example.

Some functions — I call them fun(object) use object.__func__() to do the job, or use other functions in object if there is no object.__func__()

-

For example str() - when using str(object) it calls object.__str__() , but if there is no object.__str__() , it calls object.__repr__() .

So you can use str() with an object that does not have __str__() and will still get some result.

-

Another example < - when using a < b he tries to use a.__lt__() , but if there is no a.__lt__() , he tries to use a.__gt__() (and possibly other functions too)

 class MyClass(): def __str__(self): return "MyClass: __str__" def __repr__(self): return "MyClass: __repl__" #------------------------- def __lt__(self, other): return True def __gt__(self, other): return True #------------------------- a = MyClass() b = MyClass() print( str(a) ) print( a < b ) 
  • You can remove __str__ to get a different result.

  • You can change True/False to __lt__ , and you can see that this result has changed.
    Then you can remove __lt__ , and you can change True/False to __gt__ , and you will see that the result has changed again.

-2
source

Source: https://habr.com/ru/post/909376/


All Articles