以下のコードでは、魔方法__lt__()
で '<'を定義しました。最初の引数が2番目の引数よりも小さい場合はTrue
を返し、そうでない場合はFalseを返します。Python3:なぜ比較は自然に行われますか?
from functools import total_ordering
@total_ordering
class Currency:
"""
One object of class Currency stores one amount of money, dollars and cents.
"""
def __add__(self, other):
"""
returns the result of adding self to other
"""
total = Currency(self.dollars, self.cents)
total.dollars = total.dollars + other.dollars
print (other.dollars)
total.cents = total.cents + other.cents
print (other.cents)
if total.cents > 100:
total.cents = total.cents - 100
total.dollars = total.dollars +1
return total
def __init__(self, dollars=0, cents=0):
self.dollars = dollars
self.cents = cents
def __str__(self):
return "$"+str(self.dollars)+"."+str(self.cents)
def __eq__(self, other):
return self.dollars==other.dollars and self.cents==other.cents
def __lt__(self, other):
if self.dollars<other.dollars:
return True
elif self.dollars > other.dollars:
return False
else: # dollars are equal
return self.cents < other.cents
は、そして私は '<' でテストプログラムで__lt__()
と呼ばれます。この場合、candyPrice
(最初の引数)はbookPrice
(2番目の引数)より小さいため、期待通りにTrue
を返します。そして、私はこれらの2つの値をclass Currency
であらかじめ定義されていない '>'と比較しましたが、期待通りにFalse
を返しました。 __lt__()
が既に定義されているのであれば、逆の表現である '>'式も暗黙的に定義されているのでしょうか?
if __name__ == "__main__":
candyPrice = Currency (1, 17) # $1.17
bookPrice = Currency (12, 99) # $12.99
print (candyPrice < bookPrice)
print (candyPrice > bookPrice)
同じ価格の引数を使用してプログラムをテストしましたか? – Kairat
@Kairatはい、しました。そして私はそれを私の質問に加えます。ありがとうございます –
比較に 'print'文を入れてみてください。それは呼び出されているものを表示します。一般的に、* no *、 '__gt__'は定義されていません。'__rle__'のようなものを定義すると' candy> book'は 'book
dwanderson