python - 当原始变量更新时,如何设置依赖于另一个变量的变量来更新?
问题描述
在 python 中,让我们运行以下代码行:
x = 0
y = x
x += 1
print(y)
print(x)
第一行输出明显不同于第二行,尽管我们x=y
在第 2 行设置。任何有整体编程经验的人都知道这一点。
但是,有没有办法像这样进行x
更新y
?
解决方案
我正在使用观察者设计模式:
#!/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
推荐阅读
- python - Create new variable based on groupby & value comparison
- php - 当父级是公共的时,如何将子构造函数设为私有?
- javascript - 有没有办法过滤我们的树显示的内容?
- ruby-on-rails - Active Storage Permanent Image URL
- java - How to link a JFrame class with another JPanel using JButton
- ms-access - Access 2010 报告的最后一个记录问题
- java - Android Studio - Click item in listview, get a value from that position
- mfc - 是否有自动化工具或技术可以让我读取 MFC 网格控件的内容
- gnupg - private-keys-v1.d 目录下的哪个私钥文件属于哪个密钥?
- typescript - 打字稿:无法访问命名空间接口