問題有關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'而不是將一個數字與一個對象進行比較 –