问题有关Python操作首要:__ge__
(对应于 '> =')结果未如预期Python的操作者首要:__ge__结果未如预期
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 than
'''
return self.pages < other
def ___le__(self, other):
'''
less than 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 than or equals
'''
return self.pages >= other
def __gt__(self, other):
'''
larger than
'''
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
结果一个控制台是:
766.3
False
True
最后一条语句显然是不正确的:381.3> 385和381.3> = 385显然都是假的,但最后打印的行是真的。
这是由这个Book类中的实现错误还是Python的一些内部错误引起的?我正在使用Python 2.7.10.3
也许你应该使用'other.pages'而不是将一个数字与一个对象进行比较 –