首页 > 解决方案 > 当原始变量更新时,如何设置依赖于另一个变量的变量来更新?

问题描述

在 python 中,让我们运行以下代码行:

x = 0
y = x
x += 1
print(y)
print(x)

第一行输出明显不同于第二行,尽管我们x=y在第 2 行设置。任何有整体编程经验的人都知道这一点。

但是,有没有办法像这样进行x更新y

标签: pythonvariables

解决方案


我正在使用观察者设计模式

#!/usr/bin/env python
# -*-coding: utf-8 -*-


class X:
    def __init__(self, subject):
        self.subject = subject
        self.subject.register(self)
        self.update()

    def update(self):
        self.data = self.subject.data


class Y:
    def __init__(self, data=10):
        self.data = data
        self._observers = list()

    def set(self, value):
        self.data = value
        self.notify()

    def register(self, observer):
        self._observers.append(observer)

    def notify(self):
        for ob in self._observers:
            ob.update()


y = Y(1)
x = X(y)
assert x.data == 1 and y.data == 1

y.set(20)
assert x.data == 20 and y.data == 20

y.set(-1)
assert x.data == -1 and y.data == -1

推荐阅读