设计一个二维向量类实现向量的加法减法
时间: 2024-05-01 12:21:56 浏览: 9
好的,我可以为您设计一个二维向量类。以下是代码示例:
```python
class Vector2D:
def __init__(self, x, y):
self.x = x
self.y = y
def __add__(self, other):
return Vector2D(self.x + other.x, self.y + other.y)
def __sub__(self, other):
return Vector2D(self.x - other.x, self.y - other.y)
def __str__(self):
return "({}, {})".format(self.x, self.y)
```
在这个类中,我们使用了特殊的 Python 方法来实现向量的加法和减法。`__add__` 方法用于向量加法,`__sub__` 方法用于向量减法。我们还重写了 `__str__` 方法,以便可以打印向量对象。
以下是使用该类的示例:
```python
# 创建向量
v1 = Vector2D(2, 3)
v2 = Vector2D(1, 4)
# 向量加法
v3 = v1 + v2
print("v1 + v2 =", v3)
# 向量减法
v4 = v1 - v2
print("v1 - v2 =", v4)
```
输出结果为:
```
v1 + v2 = (3, 7)
v1 - v2 = (1, -1)
```
希望这个二维向量类能够满足您的需求!