如何過載 Python 比較運算子?


Python 有魔術方法,用於定義運算子的過載行為。可以透過提供對 __lt__, __le__, __gt__, __ge__, __eq__ 和 __ne__ 魔術方法的定義來過載比較運算子(<、<=、>、>=、== 和 !=)。

以下程式過載 == 和 >= 運算子,以比較距離類的物件。

class distance:
      def __init__(self, x=5,y=5):
            self.ft=x
            self.inch=y

      def __eq__(self, other):
             if self.ft==other.ft and self.inch==other.inch:
                  return "both objects are equal"
             else:
                  return "both objects are not equal"

       def __ge__(self, other):
                 in1=self.ft*12+self.inch
                 in2=other.ft*12+other.inch
                 if in1>=in2:
                    return "first object greater than or equal to other"
                  else:
                    return "first object smaller than other"

d1=distance(5,5)
d2=distance()
print (d1==d2)
d3=distance()
d4=distance(6,10)
print (d1==d2)
d5=distance(3,11)
d6=distance()
print(d5>=d6)

以上程式的結果顯示了 == 和 >= 比較運算子的過載用法

both objects are equal
both objects are equal
first object smaller than other

更新於:02-03-2020

13K+ 瀏覽

開啟你的 職業生涯

完成課程即可獲得認證

開始學習
廣告
© . All rights reserved.