面向对象高阶-11运算符重载

常用类的运算符

__gt__
大于
__lt__
小于
__eq__
等于

!!!注意

运算符远不止这些!!!!!可以再object类中进行查看!!
当我们在使用某个符号时,python解释器都会为这个符号定义一个含义,同时调用对应的处理函数, 当我们需要自定义对象的比较规则时,就可在子类中覆盖 大于 等于 等一系列方法....

案例:

原本自定义对象无法直接使用大于小于来进行比较 ,我们可自定义运算符来实现,让自定义对象也支持比较运算符

class Student(object):
    def __init__(self,name,height,age):
        self.name = name
        self.height = height
        self.age = age

    def __gt__(self, other):
        # print(self)
        # print(other)
        # print("__gt__")
        return self.height > other.height
    
    def __lt__(self, other):
        return self.height < other.height

    def __eq__(self, other):
        if self.name == other.name and  self.age == other.age and self.height == other.height:
            return True
        return False

stu1 = Student("jack",180,28)
stu2 = Student("jack",180,28)
# print(stu1 < stu2)
print(stu1 == stu2)

Ps:

上述代码中,other指的是另一个参与比较的对象,
大于和小于只要实现一个即可,符号如果不同 解释器会自动交换两个对象的位置

posted @ 2019-09-21 10:56  suren_apan  阅读(81)  评论(0编辑  收藏  举报