[英]How can I set a variable within a class to include another variable and update when the other value changes?
[英]How do I Set Variable Dependent on Another Variable to Update when the Original Variable Updates?
在 python 中,让我们运行以下代码行:
x = 0
y = x
x += 1
print(y)
print(x)
尽管我们在第 2 行中设置了x=y
,但第一行的输出显然与第二行不同。任何有整体编程经验的人都知道这一点。
但是,有没有办法让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
要扩展@juanpa 的评论,如果将值包装在列表中,您可以获得此行为:
x = [0]
y = x
x[0] += 1
print(y[0])
print(x[0])
x = 1
y = lambda: x
x += 2
print(x, y())
不完全是您的要求,但我认为值得一提,根据您的用例,这可以解决您的问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.