什么是运算符重载
- 通过实现类中的相应的魔法方法,来让当前类的对象支持响应的运算符
注意: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)














网友评论