如何重载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 "两个对象相等"
else:
return "两个对象不相等"
def __ge__(self, other):
in1=self.ft*12+self.inch
in2=other.ft*12+other.inch
if in1>=in2:
return "第一个对象大于或等于另一个对象"
else:
return "第一个对象小于另一个对象"
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)
以上程序的结果显示了对和>=比较运算符的重载使用。
两个对象相等
两个对象相等
第一个对象小于另一个对象
阅读更多:Python 教程