用python设计一个三维变量类,实现向量的加法减法和向量与标量的乘除法运算
时间: 2024-11-15 14:34:10 浏览: 24
在Python中,我们可以创建一个名为`Vector3D`的类,用于表示三维向量,并实现加法、减法、标量乘法和除法。这里是一个基础的实现:
```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("Cannot add a Vector to a non-vector")
# 向量减法
def subtract(self, other):
if isinstance(other, Vector3D):
return Vector3D(self.x - other.x, self.y - other.y, self.z - other.z)
else:
raise ValueError("Cannot subtract a Vector from a non-vector")
# 向量与标量乘法
def scale(self, scalar):
if isinstance(scalar, (int, float)):
return Vector3D(self.x * scalar, self.y * scalar, self.z * scalar)
else:
raise ValueError("Scaling factor must be a number")
# 向量除法(实际上这是缩放操作,因为向量除以标量并不常见)
def divide(self, scalar):
if isinstance(scalar, (int, float)) and scalar != 0:
return Vector3D(self.x / scalar, self.y / scalar, self.z / scalar)
else:
raise ValueError("Cannot divide a vector by zero or a non-number")
# 示例用法
v1 = Vector3D(1, 2, 3)
v2 = Vector3D(4, 5, 6)
print("Addition:", v1.add(v2))
print("Subtraction:", v1.subtract(v2))
print("Multiplication:", v1.scale(2))
print("Division (scaled):", v1.divide(2))
```
阅读全文
相关推荐
















