)设计一个三维向量类Vector3D,包含三维向量的一些基本运算,如加法、减法以及点乘、叉乘。如v1 = (1, 2, 3),v2 = (4, 5, 6),运行效果如图1所示。
时间: 2024-02-11 22:04:14 浏览: 42
好的,我来设计一个三维向量类Vector3D,并实现基本运算。
```python
class Vector3D:
def __init__(self, x, y, z):
self.x = x
self.y = y
self.z = z
def __add__(self, other):
return Vector3D(self.x + other.x, self.y + other.y, self.z + other.z)
def __sub__(self, other):
return Vector3D(self.x - other.x, self.y - other.y, self.z - other.z)
def dot(self, other):
return self.x * other.x + self.y * other.y + self.z * other.z
def cross(self, other):
return Vector3D(self.y * other.z - self.z * other.y,
self.z * other.x - self.x * other.z,
self.x * other.y - self.y * other.x)
def __str__(self):
return f"({self.x}, {self.y}, {self.z})"
```
在上面的代码中,我们定义了一个类Vector3D,并实现了该类的构造函数、加法、减法、点乘、叉乘以及字符串表示方法。其中加法和减法使用了Python中的特殊方法`__add__`和`__sub__`,点乘和叉乘分别实现了`dot`和`cross`方法。
下面我们测试一下这个类:
```python
v1 = Vector3D(1, 2, 3)
v2 = Vector3D(4, 5, 6)
print("v1 =", v1)
print("v2 =", v2)
print("v1 + v2 =", v1 + v2)
print("v1 - v2 =", v1 - v2)
print("v1 · v2 =", v1.dot(v2))
print("v1 × v2 =", v1.cross(v2))
```
输出结果如下:
```
v1 = (1, 2, 3)
v2 = (4, 5, 6)
v1 + v2 = (5, 7, 9)
v1 - v2 = (-3, -3, -3)
v1 · v2 = 32
v1 × v2 = (-3, 6, -3)
```
可以看到,我们成功地定义了一个三维向量类Vector3D,并实现了基本运算。