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

Update self variable within __init__ everytime it is called in python

我希望 init 中的自变量在每次调用时更新,例如每次我执行 Data(10).plot 时,self.plot 都应该通过将 self.n 解析为 Plot class.

来重新初始化
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。如何在上述 classes 中实现此行为?

data = Data(10)
data.minus(2)
answer = vcf.plot.double())

Data-对象中不需要 n

class Data(object):
    def __init__(self, n):
        self.plot = Plot(n)

    def minus(self, x):
        self.plot.n -= x    


class Plot(object):
    def __init__(self, n):
        self.n = n

    def double(self):
        return self.n * 2

你要的是property。这是一种特殊类型的属性,在获取值时调用自定义 getter 函数,因此您可以动态地使其 return 正确的绘图。

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

另一种方法是 link 绘制数据,因此当数据发生变化时,绘制也会发生变化。一种方法是将它作为一个属性,所以当它改变时,属性也会改变。

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