python运算符重载
时间: 2023-10-12 17:17:07 浏览: 44
在 Python 中,运算符重载是指通过定义类的特殊方法来实现自定义运算符的行为。这些特殊方法的名称以双下划线开头和结尾,例如 `__add__` 表示重载加法运算符。
下面是一些常用的运算符重载方法:
- `__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)`:定义小于运算符 `<` 的行为。
- `__le__(self, other)`:定义小于等于运算符 `<=` 的行为。
- `__gt__(self, other)`:定义大于运算符 `>` 的行为。
- `__ge__(self, other)`:定义大于等于运算符 `>=` 的行为。
例如,我们可以定义一个名为 `Vector` 的类来表示二维向量,并重载加法运算符 `+`:
```python
class Vector:
def __init__(self, x, y):
self.x = x
self.y = y
def __add__(self, other):
return Vector(self.x + other.x, self.y + other.y)
```
现在我们就可以像下面这样使用 `+` 运算符来计算两个向量的和了:
```python
v1 = Vector(1, 2)
v2 = Vector(2, 3)
v3 = v1 + v2
print(v3.x, v3.y) # 输出 3 5
```