我希望 init 中的 self 变量在每次调用时进行更新,例如每次执行 Data(10).plot
时,self.plot 都应该通过将 self.n 解析为 Plot 类来重新初始化。
class Data(object):
def __init__(self, n):
self.n = n
self.plot = Plot(self.n)
def minus(self, x):
self.n -= x
return self.n
class Plot(object):
def __init__(self, n):
self.n = n
def double(self):
return self.n * 2
另一个例子:当我执行以下代码时,我希望答案变量等于 16。相反,它等于 20。如何在上述类中实现此行为?
data = Data(10)
data.minus(2)
answer = vcf.plot.double())
最佳答案
你想要的是 property
。这是一种特殊类型的属性,在获取值时调用自定义 getter 函数,因此您可以使其动态返回正确的绘图。
class Data(object):
def __init__(self, n):
self.n = n
@property
def plot(self):
return Plot(self.n)
def __sub__(self, x):
return Data(self.n - x)
作为旁注,请查看 the data model覆盖 python 运算符。
data = Data(10)
data -= 2
answer = data.plot.double() # Calls the `plot()` function to get a value for `data.plot`.
print(answer) # 16
另一种方法是将绘图链接到数据,这样当数据发生变化时,绘图也会发生变化。一种方法就是将其作为属性,因此当它更改时,属性也会更改。
class Plot(object):
def __init__(self, data):
self.data = data
@property
def n(self):
return self.data.n
@n.setter
def n(self, x):
self.data.n = x
def double(self):
return self.n * 2
data = Data(10)
plot = Plot(data)
data.minus(2)
answer = plot.double() # 16
关于python - 每次在 python 中调用时都会更新 __init__ 中的 self 变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44345586/