class Bar:
def __init__(self, n):
self.n = n
class Foo:
def __init__(self, l):
self.l = l
x = Bar(2)
# we want x.n to change whenever y.l changes
y = Foo(x.n)
# I'd like x.n to become 3 as a result
y.l += 1
print(x.n)
>>> 2
我该如何做才能x.n
从内部进行更改y
?没有向其中添加更多功能的简便方法x
吗?
嗯,正如其他人已经指出的那样,问题归结为您正在处理不可移植对象的事实。在意识到这一点之后,您应该使用可变类型,或者使用回调来管理更新。Adriano Abrantes给出了使用可变类型的替代方法的示例,但是如果您不是要查找的类型,那么这里是潜在的回调系统的示例:
# bad habit to be using the old style class definition (i.e. `class Foo:`)
# the `@property` decorator wont work if you use the old style
class Sync(object):
def __init__(self, name, value, *dependants):
"""Sync the attribute `name` on all `dependants` when `self.value` is updated"""
self._name = name
self._value = value
self._updating = False
self._dependants = list(dependants)
self._update_dependants()
@property
def value(self):
return self._value
@value.setter
def value(self, x):
if x != self._value:
self._value = x
self._update_dependants()
def _update_dependants(self):
self._updating = True
for d in self._dependants:
if getattr(d, self._name) != self.value:
if isinstance(d, Sync):
if not d._updating:
setattr(d, self._name, self.value)
else:
setattr(d, self._name, self.value)
self._updating = False
def add_dependant(self, other):
self._dependants.append(other)
self._update_dependants()
def del_dependnant(self, other):
self._dependants.remove(other)
def __repr__(self):
return "Sync('"+self._name+"': "+repr(self.value)+")"
def __eq__(self, other):
if isinstance(other, Sync):
return self.value == other.value
else:
return self.value == other
def __ne__(self, other):
return not self.__eq__(other)
s1 = Sync('value', 2)
s2 = Sync('value', 1)
print('setup the Sync objects:')
print('>>> ' + repr(s1) + (' == ' if s1 == s2 else ' != ') + repr(s2))
s1.add_dependant(s2)
s2.add_dependant(s1)
print('add sync objects as dependants of each other:')
print('>>> ' + repr(s1) + (' == ' if s1 == s2 else ' != ') + repr(s2))
s1.value += 1
print('check that value changes transfer from one to the other:')
print('>>> ' + repr(s1) + (' == ' if s1 == s2 else ' != ') + repr(s2))
如果这仍然不能使您满意,我将研究一种名为Traitlets的东西。这是Ipython的一个软件包,是Jupyter项目的一部分,该软件包可进行类型检查,简化回调系统并简化应用程序的配置。我已经为这个项目做过一段时间了,因此,如果您对Traitlets有任何疑问,请随时在这里询问我或将其发布在Gitter上,开发团队将为您解答。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句