第三十一章、运算符重载
1. 算术运算符重载
什么是运算符重载?
运算符重载是指通过自定义类中的特殊方法来让自定义的类创建的对象可以使用运算符(如 +、-等)进行操作。
作用
- 让类的便于使用。
- 让代码简洁易读。
- 重新定义运算符的运算规则。
算术运算符重载
方法名和参数
运算符和表达式
说明
__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
幂
__matmul__(self, other)
self @ other
矩阵乘法
说明:
- 运算符重载方法的参数已经有固定的含义,不建议改变原有的意义
- 重载后的运算符,不会改变运算符的优先级。
二元运算符重载方法格式:
def __xxx__(self, other):
....
对于算术运算符, self参数绑定运算符左侧的对象,other 绑定运算符右侧的对象。
示例
# 算术运算符重载 示例
# http://weimingze.com
class Vector3D:
'''用于描述三维向量的类!,x,y,z分别是向量的坐标位置!'''
def __init__(self, x, y, z):
self.x, self.y, self.z = x, y, z
def __repr__(self):
return f'Vector3D({self.x},{self.y},{self.z})'
def __add__(self, other):
return Vector3D(self.x + other.x,
self.y + other.y,
self.z + other.z)
v1 = Vector3D(1, 2, 3)
v2 = Vector3D(4, 5, 6)
print("v1:", v1)
print("v2:", v2)
v3 = v1 + v2 # 等同于 v3 = v1.__add__(v2)
print('v3:', v3)
运行结果
v1: Vector3D(1,2,3)
v2: Vector3D(4,5,6)
v3: Vector3D(5,7,9)