Why Do Tuples In Python Work With Reversed But Do Not Have __reversed__?
Solution 1:
According to the spec:
reversed(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).
Solution 2:
EDIT: well, I try to say it again (english is not my native language) - with example.
Some functions - I call them fun(object) - can use object.__func__() to do the job or they use other functions in object if there is no object.__func__()
-
For example str() - when you use str(object) it calls object.__str__(), but if there is no object.__str__() then it calls object.__repr__().
So you can use str() with object which has no __str__() and still get some result.
-
Other example < - when you use a < b it tries to use a.__lt__() but if there is no a.__lt__() it tries to use a.__gt__() (and maybe other functions too)
classMyClass():
def__str__(self):
return"MyClass: __str__"def__repr__(self):
return"MyClass: __repl__"#-------------------------def__lt__(self, other):
returnTruedef__gt__(self, other):
returnTrue#-------------------------
a = MyClass()
b = MyClass()
print( str(a) )
print( a < b )
You can remove
__str__to get different result.You can change
True/Falsein__lt__and you can see that result is changed. Then you can remove__lt__and you can changeTrue/Falsein__gt__and you see that result is changed again.
Post a Comment for "Why Do Tuples In Python Work With Reversed But Do Not Have __reversed__?"