用python写自定义类模拟三维向量及其运算。包括向量的加法、减法以及向量与标量的乘法和除法,并使用@property查看向量长度。 例如,a=(x1,y1,z1),b=(x2,y2,z2) a+b=(x1+x2,y1+y2,z1+z2),a-b=(x1-x2,y1-y2,z1-z2) n=10,a*n=(x1*n,y1*n,z1*n),a/n=(x1/n,y1/n,z1/n) a.length=(x1**2+y1**2+z1**2)**0.5
时间: 2024-02-06 19:12:46 浏览: 66
Python三维向量,单元测试unittest
好的,以下是实现代码:
```python
class Vector:
def __init__(self, x, y, z):
self.x = x
self.y = y
self.z = z
def __add__(self, other):
return Vector(self.x + other.x, self.y + other.y, self.z + other.z)
def __sub__(self, other):
return Vector(self.x - other.x, self.y - other.y, self.z - other.z)
def __mul__(self, scalar):
return Vector(self.x * scalar, self.y * scalar, self.z * scalar)
def __truediv__(self, scalar):
return Vector(self.x / scalar, self.y / scalar, self.z / scalar)
@property
def length(self):
return (self.x ** 2 + self.y ** 2 + self.z ** 2) ** 0.5
```
使用方法如下:
```python
a = Vector(1, 2, 3)
b = Vector(4, 5, 6)
print(a + b) # 输出 Vector(5, 7, 9)
print(a - b) # 输出 Vector(-3, -3, -3)
print(a * 10) # 输出 Vector(10, 20, 30)
print(a / 2) # 输出 Vector(0.5, 1.0, 1.5)
print(a.length) # 输出 3.7416573867739413
```
阅读全文