重载内置类型的运算符python
时间: 2023-09-21 21:11:13 浏览: 120
可以通过在类中定义特殊的方法来重载内置类型的运算符,例如:
- __add__(self, other):重载加法运算符 (+)
- __sub__(self, other):重载减法运算符 (-)
- __mul__(self, other):重载乘法运算符 (*)
- __truediv__(self, other):重载真除法运算符 (/)
- __floordiv__(self, other):重载整除运算符 (//)
- __mod__(self, other):重载取模运算符 (%)
- __pow__(self, other):重载幂运算符 (**)
- __eq__(self, other):重载等于运算符 (==)
- __ne__(self, other):重载不等于运算符 (!=)
- __lt__(self, other):重载小于运算符 (<)
- __gt__(self, other):重载大于运算符 (>)
- __le__(self, other):重载小于等于运算符 (<=)
- __ge__(self, other):重载大于等于运算符 (>=)
在这些特殊方法中,self代表当前对象,other代表与之运算的对象。举个例子,我们可以定义一个向量类,重载加法运算符:
```
class Vector:
def __init__(self, x, y, z):
self.x = x
self.y = y
self.z = z
def __add__(self, other):
return Vector(self.x + other.x, self.y + other.y, self.z + other.z)
v1 = Vector(1, 2, 3)
v2 = Vector(4, 5, 6)
v3 = v1 + v2
print(v3.x, v3.y, v3.z) # 输出 5 7 9
```
阅读全文