我正在尝试自动更新具有固定关系的类变量。例如:
class vector:
def __init__(self, x, y, z):
self.x = x
self.y = y
self.z = z
self.r = (x**2+y**2+z**2)**0.5
self.theta = tan((x**2+y**2)**0.5/z)
self.phi = tan(y/x)
如果我更改此类的实例的值x,我想自动更新半径和角度。而且,如果我更改角度或半径,我想自动更新x,y,z分量。有什么办法吗?
编辑:好的,我现在有以下解决方案。如果有错误或不是我的常规错误,请纠正我。
from math import tan, cos, sin
class Vector:
def __init__(self, x, y, z):
self._x = x
self._y = y
self._z = z
self._r = (self._x**2+self._y**2+self._z**2)**0.5
self._theta = tan((self._x**2+self._y**2)**0.5/self._z)
self._phi = tan(self._y/self._x)
@property
def x(self):
return self._x
@x.setter
def x(self, new_x):
self._x = new_x
self._r = (self._x**2+self._y**2+self._z**2)**0.5
self._theta = tan((self._x**2+self._y**2)**0.5/self._z)
self._phi = tan(self._y/self._x)
@property
def y(self):
return self._y
@y.setter
def y(self, new_y):
self._y = new_y
self._r = (self._x**2+self._y**2+self._z**2)**0.5
self._theta = tan((self._x**2+self._y**2)**0.5/self._z)
self._phi = tan(self._y/self._x)
@property
def z(self):
return self._z
@z.setter
def z(self, new_z):
self._z = new_z
self._r = (self.x**2+self.y**2+self.z**2)**0.5
self._theta = tan((self._x**2+self._y**2)**0.5/self._z)
self._phi = tan(self._y/self._x)
@property
def r(self):
return (self._x**2+self._y**2+self._z**2)**0.5
@r.setter
def r(self, new_r):
self._r = new_r
self._x = self._r*cos(self._theta)*cos(self._phi)
self._y = self._r*cos(self._theta)*sin(self._phi)
self._z = self._r*sin(self._theta)
@property
def theta(self):
return tan((self._x**2+self._y**2)**0.5/self._z)
@theta.setter
def theta(self, new_theta):
self._theta = new_theta
self._x = self._r*cos(self._theta)*cos(self._phi)
self._y = self._r*cos(self._theta)*sin(self._phi)
self._z = self._r*sin(self._theta)
@property
def phi(self):
return tan(self._y/self._x)
@phi.setter
def phi(self,new_phi):
self._phi = new_phi
self._x = self._r*cos(self._theta)*cos(self._phi)
self._y = self._r*cos(self._theta)*sin(self._phi)
self._z = self._r*sin(self._theta)
您正在寻找@property
装饰器,该装饰器通过函数语句设置对象的变量。]>
@property
因此,
from math import tan
class Vector:
def __init__(self, x, y, z):
self.x = x
self.y = y
self.z = z
@property
def r(self):
return (self.x**2+self.y**2+self.z**2)**0.5
@property
def theta(self):
return tan((self.x**2+self.y**2)**0.5/self.z)
@property
def phi(self):
return tan(self.y/self.x)
您可以按照以下方式重写您的课程