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

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

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

阅读更多:Python 教程

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程