首页 > 其他 > 详细

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

时间:2019-09-21 14:55:26      阅读:100      评论:0      收藏:0      [点我收藏+]

常用类的运算符

__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指的是另一个参与比较的对象,
大于和小于只要实现一个即可,符号如果不同 解释器会自动交换两个对象的位置

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

原文:https://www.cnblogs.com/suren-apan/p/11561909.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!