运算符重载
1.运算符重载
python中使用每一个运算符都是在调用运算符对应的方法(每个运算符都有自己对应的方法)
某种类型的数据支不支持某个运算符,就看这个数据对应的类型中有没有实现运算符对应的方法
# 10 + 20 # 10.__add__(20)
# 'abc' + '123' # 'abc'.__add__('123')
# 100 - 10 # 100.__sub__(10)
class Person:
def __init__(self,name='',age=0):
self.name = name
self.age = age
def __add__(self, other):
return self.age + other.age
def __mul__(self, other):
list1 = []
for _ in range (other):
list1.append(copy(self))
return list1
# 大于和小于符号实现任意一个,另一个也可以用
def __lt__(self,other):
return self.age < other.age
def __repr__(self):
return f'{str(self.__dict__)[1:-1]}'
p1 = Person(name='abc',age=18)
p2 = Person(age=238)
print(p1 == p2)
print(p1 + p2)
print(p1 * 3) # []
persons = [Person('xiaohua',20),Person('xiaoming',19),Person('huahua',21)]
persons.sort()
print(persons)
100>1