python 基础之算数运算
算术运算符 - 示例: ```python class Number: def __init__(self, num): self.num = num # 对象出现在'+'的左边时会自动触发 def __add__(self, other): print('__add__') return self.num + other # 对象出现在'+'的右边时会自动触发 def __radd__(self, other): print('__radd__') return self.num + other # +=运算时自动触发,若没有实现会调用__add__ def __iadd__(self, other): print('__iadd__') # 返回新的Number对象 # return Number(self.num + other) # 返回处理后的原始对象 self.num += other return self n = Number(10) print(id(n)) # ret = n + 20 # ret = 20 + n # print(ret) n += 50 # n = n + 50 print(id(n))
有兴趣的朋友可以继续测试
```
加法:add、radd、iadd
减法:sub、rsub、isub
乘法:mul、rmul、imul
除法:truediv、rtruediv、itruediv
求余:mod、rmod、imod
```