Python operator overriding: __ge__ result is not as expected -
problem python operator overriding: __ge__ (corresponding '>=') result not expected
class book: title = '' pages = 0 def __init__(self, title='', pages=0): self.title = title self.pages = pages def __str__(self): return self.title def __radd__(self, other): ''' enables book1 + book2 ''' return self.pages + other def __lt__(self, other): ''' less ''' return self.pages < other def ___le__(self, other): ''' less or equals ''' return self.pages <= other def __eq__(self, other): ''' equals ''' return self.pages == other def __ne__(self, other): ''' not equals ''' return self.pages != other def __ge__(self, other): ''' larger or equals ''' return self.pages >= other def __gt__(self, other): ''' larger ''' return self.pages > other book1 = book('fluency', 381.3) book2 = book('the martian', 385) book3 = book('ready player one', 386) summation = sum([book1, book2, book3]) print book1 + book2 print book1 > book2 print book1 >= book2 the result 1 console is:
766.3 false true the last statement incorrect: 381.3 > 385 , 381.3 >= 385 both false, last printed line true.
is caused implementation bugs inside book class, or inner bugs of python? using python 2.7.10.3
the problem typo: ___le__() should __le__().
however, that's unusual way implement comparison operators. compare 2 objects of same type instead of comparing number book object. that's why confusing: > operator calling __lt__() method, , >= doesn't find __le__() method. reason direction reversed number on left side of of comparison operator doesn't implement rich comparison methods, book on right does. causes reversed comparison method called.
there no swapped-argument versions of these methods (to used when left argument not support operation right argument does); rather,
__lt__(),__gt__()each other’s reflection,__le__(),__ge__()each other’s reflection, ,__eq__(),__ne__()own reflection.
i think easier understand if class implemented __cmp__().
Comments
Post a Comment