我正在尝试在 python 中制作 3D 点对象,我有以下代码
import numpy as np
class Point3D:
def __init__(self, x, y, z):
self.vector = np.matrix([x, y, z])
self.vector.reshape(3, 1)
def x(self): return self.vector.item((0, 0))
def y(self): return self.vector.item((0, 1))
def z(self): return self.vector.item((0, 2))
我正在使用 numpy 创建垂直矩阵,最终将其用于渲染引擎。例如,我希望能够引用该向量的 x、y 和 z,而无需输入
self.vector.item((0, 0))
。我希望能够执行 point.x
并自动从向量中获取 x 值。我还希望能够将值设置为:point.x = 5
。有什么办法可以实现吗?
我尝试在 init 函数的开始处设置它们,但每次都必须更新它。然后我做了函数,那里只需要额外的2个字符,但设置仍然没有实现。
您想要做的是属性获取器和设置器
import numpy as np
class Point3D:
def __init__(self, x, y, z):
self.vector = np.matrix([x, y, z]).reshape(3,1)
@property
def x(self):
return self.vector[0,0]
@property
def y(self):
return self.vector[0,1]
@property
def z(self):
return self.vector[0,2]
@x.setter
def x(self, x):
self.vector[0,0] = x
@y.setter
def y(self, y):
self.vector[0,1] = y
@z.setter
def z(self, z):
self.vector[0,2] = z