定义一个三维向量类Vector3,并实现python中的特殊方法以进行两个该类对象之间的加、减、乘、除运算(要求支持运算符+、-、*、/);实现向量长度的计算(要求使用属性实现,且该属性是可读、可写、可删除)
时间: 2023-10-27 12:21:20 浏览: 21
```python
class Vector3:
def __init__(self, x=0.0, y=0.0, z=0.0):
self.x = x
self.y = y
self.z = z
def __add__(self, other):
return Vector3(self.x + other.x, self.y + other.y, self.z + other.z)
def __sub__(self, other):
return Vector3(self.x - other.x, self.y - other.y, self.z - other.z)
def __mul__(self, scalar):
return Vector3(self.x * scalar, self.y * scalar, self.z * scalar)
def __truediv__(self, scalar):
return Vector3(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
@length.setter
def length(self, value):
length_ratio = value / self.length
self.x *= length_ratio
self.y *= length_ratio
self.z *= length_ratio
@length.deleter
def length(self):
self.x = 0.0
self.y = 0.0
self.z = 0.0
```
使用示例:
```python
v1 = Vector3(1, 2, 3)
v2 = Vector3(4, 5, 6)
v3 = v1 + v2
print(v3.x, v3.y, v3.z) # 输出:5 7 9
v4 = v2 - v1
print(v4.x, v4.y, v4.z) # 输出:3 3 3
v5 = v1 * 2
print(v5.x, v5.y, v5.z) # 输出:2 4 6
v6 = v2 / 2
print(v6.x, v6.y, v6.z) # 输出:2 2.5 3
print(v1.length) # 输出:3.7416573867739413
v1.length = 5
print(v1.x, v1.y, v1.z) # 输出:1.3416407864998738 2.6832815729997477 4.024922359499621
del v1.length
print(v1.x, v1.y, v1.z) # 输出:0.0 0.0 0.0
```