如何实现Python __lt__ __gt__自定义(重载)运算符?
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 __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
热门推荐
10 38节贺卡简短祝福语
11 嫂子生日的祝福语简短
12 宝宝周岁可乐祝福语简短
13 红颜生日祝福语简短独特
14 药店祝福语简短10字
15 夸赞老师祝福语搞笑简短
16 领证幽默祝福语简短
17 发小结婚简短祝福语
18 祖国七十华诞简短祝福语