设计一个三维向量类,并实现向量的加法、减法以及向量与标量的乘法和除法运算。 示例操作如下: (1,2,3) + (4,5,6) =(5,7,9) (5,7,9) - (2,3,4) =(3,4,5) (1,2,3)*3 = (3,6,9) (4,8,12)/2 = (2,4,6)
时间: 2023-10-04 10:10:48 浏览: 82
以下是一个基本的三维向量类的实现,包括加法、减法、标量乘法和标量除法的运算重载:
```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)
```
使用示例:
```python
v1 = Vector3D(1, 2, 3)
v2 = Vector3D(4, 5, 6)
# 向量加法
v3 = v1 + v2
print(v3.x, v3.y, v3.z) # 输出:5 7 9
# 向量减法
v4 = v3 - Vector3D(2, 3, 4)
print(v4.x, v4.y, v4.z) # 输出:3 4 5
# 向量标量乘法
v5 = v1 * 3
print(v5.x, v5.y, v5.z) # 输出:3 6 9
# 向量标量除法
v6 = Vector3D(4, 8, 12) / 2
print(v6.x, v6.y, v6.z) # 输出:2 4 6
```
注意:这只是一个基本的实现示例,实际的向量类可能需要更多的功能和运算符重载。
阅读全文