在 Python 中,使用自定义类模拟三维向量及其运算可通过定义一个类并实现相应的特殊方法达成。以下为两种实现方式:
### 方式一
定义一个 `Vector3` 类,通过特殊方法实现运算符重载,支持向量间的加、减运算,以及向量与标量的乘、除运算,同时使用属性计算向量长度。
```python
class Vector3:
# 构造方法,初始化,定义向量坐标
def __init__(self, x, y, z):
self.__x = x
self.__y = y
self.__z = z
# 与另一个向量相加,对应分量相加,返回新向量
def __add__(self, anotherPoint):
x = self.__x + anotherPoint.__x
y = self.__y + anotherPoint.__y
z = self.__z + anotherPoint.__z
return Vector3(x, y, z)
# 减去另一个向量,对应分量相减,返回新向量
def __sub__(self, anotherPoint):
x = self.__x - anotherPoint.__x
y = self.__y - anotherPoint.__y
z = self.__z - anotherPoint.__z
return Vector3(x, y, z)
# 向量与一个数字相乘,各分量乘以同一个数字,返回新向量
def __mul__(self, n):
x, y, z = self.__x * n, self.__y * n, self.__z * n
return Vector3(x, y, z)
# 向量除以一个数字,各分量除以同一个数字,返回新向量
def __truediv__(self, n):
x, y, z = self.__x / n, self.__y / n, self.__z / n
return Vector3(x, y, z)
# 查看向量长度,所有分量平方和的平方根
@property
def length(self):
return (self.__x**2 + self.__y**2 + self.__z**2)**0.5
def __str__(self):
return 'Vector3({},{},{})'.format(self.__x, self.__y, self.__z)
```
使用示例:
```python
v1 = Vector3(1, 2, 3)
v2 = Vector3(4, 5, 6)
print(v1 + v2)
print(v1 - v2)
print(v1 * 2)
print(v1 / 2)
print(v1.length)
```
### 方式二
定义一个 `MyArray` 类,通过普通方法实现向量间的加、减运算,以及向量与标量的乘、除运算,并计算向量长度,同时在方法中直接输出结果。
```python
class MyArray:
def __init__(self, x, y, z):
self.__x = x
self.__y = y
self.__z = z
def add(self, a):
x = self.__x + a.__x
y = self.__y + a.__y
z = self.__z + a.__z
print("和=({},{},{})".format(x, y, z))
def sub(self, a):
x = self.__x - a.__x
y = self.__y - a.__y
z = self.__z - a.__z
print("差=({},{},{})".format(x, y, z))
def mul(self, a):
x = self.__x * a
y = self.__y * a
z = self.__z * a
print("乘积=({},{},{})".format(x, y, z))
def truediv(self, a):
x = self.__x / a
y = self.__y / a
z = self.__z / a
print("商=({},{},{})".format(x, y, z))
def length(self):
a = pow(pow(self.__x, 2) + pow(self.__y, 2) + pow(self.__z, 2), 0.5)
print("长度为:{}".format(round(a, 3)))
print('请输入六个数a,b,c,d,e,f:')
a, b, c, d, e, f = map(int, input().split())
print('N1:', (a, b, c))
print('N2:', (d, e, f))
n1 = MyArray(a, b, c)
n2 = MyArray(d, e, f)
n1.add(n2)
n1.sub(n2)
n1.mul(2)
n1.truediv(2)
n1.length()
```
这两种方式都能实现使用自定义类模拟三维向量及其运算的功能,方式一借助运算符重载,代码更简洁直观;方式二则通过普通方法输出结果,适合需要直接展示运算结果的场景 [^1][^2][^4]。