用python设计一个三维向量类,并实现向量的加法减法以及向量与标量的乘法和除法运算
时间: 2025-01-27 20:06:50 浏览: 54
在Python中,我们可以设计一个简单的三维向量类,包括初始化、加法、减法、标量乘法和标量除法等方法。这里给出一个基础实现:
```python
class Vector3D:
def __init__(self, x=0, y=0, z=0):
self.x = x
self.y = y
self.z = z
# 向量加法
def __add__(self, other):
if isinstance(other, Vector3D):
return Vector3D(self.x + other.x, self.y + other.y, self.z + other.z)
else:
raise ValueError("加法只支持向量对象")
# 向量减法
def __sub__(self, other):
if isinstance(other, Vector3D):
return Vector3D(self.x - other.x, self.y - other.y, self.z - other.z)
else:
raise ValueError("减法只支持向量对象")
# 标量乘法
def scale(self, scalar):
if isinstance(scalar, (int, float)):
return Vector3D(self.x * scalar, self.y * scalar, self.z * scalar)
else:
raise TypeError("乘法只支持标量")
# 尝试性的实现标量除法,如果除数为零会抛出异常
def __truediv__(self, scalar):
if isinstance(scalar, (int, float)) and scalar != 0:
return Vector3D(self.x / scalar, self.y / scalar, self.z / scalar)
else:
raise ZeroDivisionError("除数不能为零")
# 示例
vector1 = Vector3D(1, 2, 3)
vector2 = Vector3D(4, 5, 6)
print(vector1 + vector2) # 输出: Vector3D(x=5, y=7, z=9)
print(vector1 - vector2) # 输出: Vector3D(x=-3, y=-3, z=-3)
print(vector1.scale(2)) # 输出: Vector3D(x=2, y=4, z=6)
try:
print(vector1 / 0) # 抛出ZeroDivisionError
except ZeroDivisionError as e:
print(e)
```
请注意,上述代码中的除法操作并未完全处理所有可能的边缘情况,例如除数为0的情况。实际应用中可能需要更全面的错误处理。
阅读全文