美文网首页
运算符重载

运算符重载

作者: 匿隱 | 来源:发表于2019-02-12 09:33 被阅读0次

    1.什么是运算符重载

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

    注意:python中所有的数据类型都是类; 所有的数据都是对象

    class Student(object):
        def __init__(self, name='', age=0, score=0):
            self.name = name
            self.age = age
            self.score = score
    
        def __repr__(self):
            return '<' + str(self.__dict__)[1:-1] + '>'
    

    实现'+'对应的魔法方法,让两个学生对象能够进行+操作
    self和other的关系: self+other ==> self.add(other)
    返回值就是运算结果

        def __add__(self, other):
            # a.支持Student+Student:
            return self.age + other.age
            # b.支持Student+数字
            # return self.age + other
    
        # self * other
        # 将other当成数字
        def __mul__(self, other):
            return self.name * other
    
        # self和other都是学生对象
        # 注意:大于和小于运算符是需要重载一个就行
        def __gt__(self, other):
            return self.score > other.score
    
    
    def main():
        stu1 = Student('小花', 18, 90)
        stu2 = Student('夏明', 20, 78)
        stu3 = Student('小红', 17, 99)
    
        # 所有类的对象都支持'=='和'!='运算
        print(stu1 == stu2)
    
        print(stu1 + stu2)     # print(stu1.__add__(stu2))
    
        # print(stu1 > stu2)
        # print(stu1 < stu2)
    
        print(stu1 * 2)   # print(stu1.__mul__(2))
    
        students = [stu1, stu2, stu3]
        print(students)
        students.sort()
        print(students)
    

    相关文章

      网友评论

          本文标题:运算符重载

          本文链接:https://www.haomeiwen.com/subject/zuxljqtx.html