什么是运算符重载:
让自定义的类生成的对象(实例)能够使用运算符进行操作.
算数运算符重载:
方法名 运算符和表达式 说明
__add__(self,other) self + other 加法
__sub__(self,other) self - other 减法
__mul__(self,other) self * other 乘法
__truediv__(self,other) self / other 除法
__floordiv__(self,other) self // other 地板除
__mod__(self,other) self % other 取模(求余)
__pow__(self,other) self **other 幂运算
class Person:
def __init__(self,num):
self.num = num
def __add__(self, other):
return Person(self.num + other.num)
def __sub__(self, other):
return Person(self.num - other.num)
def __str__(self):
return "num = "+str(self.num)
p1 = Person(12)
p2 = Person(13)
print(p1+p2)
print(p1-p2)
F:\学习代码\Python代码\venv\Scripts\python.exe F:/学习代码/Python代码/day5/运算符重载2.py
num = 25
num = -1
Process finished wit