用Python设计一个三维向量类,并实现向量的加法、减法以及向量与标量的乘法和除法运算
时间: 2024-05-07 14:23:01 浏览: 120
python中三维向量的运算
5星 · 资源好评率100%
可以按照以下方式实现一个三维向量类:
```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 __mul__(self, scalar):
return Vector3D(self.x * scalar, self.y * scalar, self.z * scalar)
def __truediv__(self, scalar):
return Vector3D(self.x / scalar, self.y / scalar, self.z / scalar)
def __str__(self):
return f"({self.x}, {self.y}, {self.z})"
```
然后,可以创建两个向量并测试它们的加、减、乘和除运算:
```python
v1 = Vector3D(1, 2, 3)
v2 = Vector3D(4, 5, 6)
print(v1 + v2) # 输出 (5, 7, 9)
print(v1 - v2) # 输出 (-3, -3, -3)
print(v1 * 2) # 输出 (2, 4, 6)
print(v2 / 3) # 输出 (1.3333333333333333, 1.6666666666666667, 2.0)
```
阅读全文