如何实现 Python __lt__ __gt__ 自定义(重载)运算符?


Python 拥有魔法方法来定义运算符的重载行为。可以通过为 __lt__、__le__、__gt__、__ge__、__eq__ 和 __ne__ 魔法方法提供定义来重载比较运算符(<、<=、>、>=、== 和 !=)。以下程序重载 < 和 > 运算符来比较 distance 类的对象。 

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 __lt__(self, other):
    in1=self.ft*12+self.inch
    in2=other.ft*12+other.inch
    if in1<in2:
      return "first object smaller than other"
    else:
      return "first object not smaller than other"

  def __gt__(self, other):
    in1=self.ft*12+self.inch
    in2=other.ft*12+other.inch
    if in1<in2:
      return "first object greater than other"
    else:
      return "first object not greater 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)

结果展示了 __lt__ 和 _gt__ 魔法方法的实现

first object not greater than other
first object not smaller than other
first object smaller than other

更新于: 02-Mar-2020

3000+ 浏览

启动您的 职业

完成课程,获得认证

开始
广告
© . All rights reserved.