gpt4 book ai didi

python - 每次在 python 中调用时更新 __init__ 中的自变量

转载 作者:太空宇宙 更新时间:2023-11-04 09:59:34 25 4
gpt4 key购买 nike

我希望 init 中的自变量在每次调用时更新,例如每次我执行 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

另一个示例:当我执行以下代码时,我希望 answer 变量等于 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__ 中的自变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44345586/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com