python代码实现:定义一个三维向量类Vector3,并实现python中的特殊方法以进行两个该类对象之间的加、减、乘、除运算(要求支持运算符+、-、*、/);实现向量长度的计算(要求使用属性实现,且该属性是可读、可写、可删除),并且调用所有方法
时间: 2023-07-10 19:24:35 浏览: 161
用Python自定义三维向量类,实现加减乘除等运算
以下是代码实现:
```python
class Vector3:
def __init__(self, x, y, z):
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, other):
return Vector3(self.x * other, self.y * other, self.z * other)
def __truediv__(self, other):
return Vector3(self.x / other, self.y / other, self.z / other)
def __len__(self):
return (self.x ** 2 + self.y ** 2 + self.z ** 2) ** 0.5
def __str__(self):
return "Vector3({0}, {1}, {2})".format(self.x, self.y, self.z)
def __repr__(self):
return self.__str__()
def __setattr__(self, name, value):
if name in ['x', 'y', 'z']:
object.__setattr__(self, name, value)
else:
raise AttributeError("Vector3 object has no attribute '{0}'".format(name))
def __delattr__(self, name):
if name in ['x', 'y', 'z']:
object.__delattr__(self, name)
else:
raise AttributeError("Vector3 object has no attribute '{0}'".format(name))
# 测试
v1 = Vector3(1, 2, 3)
v2 = Vector3(4, 5, 6)
print(v1 + v2) # 输出: Vector3(5, 7, 9)
print(v1 - v2) # 输出: Vector3(-3, -3, -3)
print(v1 * 2) # 输出: Vector3(2, 4, 6)
print(v2 / 2) # 输出: Vector3(2.0, 2.5, 3.0)
print(len(v1)) # 输出: 3.7416573867739413
v1.x = 10 # 设置属性值
print(v1) # 输出: Vector3(10, 2, 3)
del v1.y # 删除属性
print(v1) # 输出: Vector3(10, 0, 3)
```
阅读全文