如何重载Python比较运算符?
Python具有神奇的方法来定义运算符的重载行为。比较运算符(<,<=,>,>=,==和!=)可以通过为__lt__,__le__,__gt__,__ge__,eqeq和__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
热门推荐
10 诗词送行祝福语大全简短
11 新房开工吉日祝福语简短
12 50多岁生日简短祝福语
13 安徽疫情祝福语简短英语
14 农民朋友发财祝福语简短
15 对生活祝福语简短精辟
16 搬家词简短祝福语朋友
17 女神结婚快乐祝福语简短
18 文学短句祝福语大全简短