01.14 - 运算符重载

什么是运算符重载

  • 通过实现类中的相应的魔法方法,来让当前类的对象支持响应的运算符

注意:python中所有的数据类型都是类;所有的数据都是对象,所有类的对象都支持==和!=运算符,其他的必须靠魔法方法实现

  • 加号对应的魔法方法:__add__,让两个对象能够进行+操作,有两个参数,一个self,一个other,self指的是加号前的对象,other是加号后的对象,返回值为运算结果

  • 乘号对应的魔法方法:__mul__

  • 大于对应的魔法方法:__gt__,若有大于类,小于也会有,对结果去反

class Ql_Student(object):  # 
    """ 
    类说明文档:
    """
    def __init__(self, name, age, score):
        """
        函数说明文档:
        """
        self.name = name
        self.age = age
        self.score = score
    
    def __add__(self, other):
        return self.age + other.age
    
    def __mul__(self, other):
        return self.name * other
    
    def __gt__(self, other):
        return self.score > other.score
    
    def __repr__(self):
        return '<' + str(self.__dict__)[1:-1] + '>'


    


def main():
    stu1 = Ql_Student('小花', 18, 90)
    stu2 = Ql_Student('小明', 20, 78)
    stu3 = Ql_Student('小红', 19, 80)
    print(stu1 == stu2)
    print(stu1 + stu2)
    print(stu1 * 2)
    print(stu1 < stu2)
    students = [stu1, stu2, stu3]
    print(sorted(students, key = lambda x:x.score))
    print('*' * 50 )
    students.sort()
    print(students)


©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容