我有一个 python 问题(为了示例而在此处进行了简化),其中我有 2 个类:一个子类(要注入)和一个父类。在父类中,我有一个存储子类实例的属性(通过依赖注入)。该属性有一个 getter 和一个 setter。
我想要实现的是,当子实例中的(任何)属性发生更改(在父类之外)时,会发生一些事情。但是,在下面的示例中,什么也没有发生。触发设置器的唯一方法是用另一个实例替换子类(我不想要)。
class Spline3D:
def __init__(self, num=20):
self.num = num
class Spline3DViewer:
def __init__(self, spline3D):
self._spline3D = spline3D
@property
def spline3D(self):
return self._spline3D
@spline3D.setter
def spline3D(self, value):
self._spline3D = value
print(f"Updated self.spline3D.num is = {self._spline3D.num}")
spline3D = Spline3D(num=30)
spline3DViewer = Spline3DVTK(spline3D=spline3D)
spline3D.num = 40 ### This should, technically, trigger the @spline3D.setter in Spline3DViewer
and print "Updated self.spline3D.num is = 40" but nothing happens
但是,这有效(不是我想要的解决方案):
spline3D2 = Spline3D(num=40)
spline3DViewer.spline3D = spline3D2
我显然做错了什么,但我似乎找不到解决方案。如有任何帮助,我们将不胜感激。
亲切的问候,
你这么说
从技术上讲,这应该触发@spline3D.setter
但不应该。仅当您为 spline3DViewer 的 spline3D 字段分配新值时才会调用 setter,而不是在更改 spline3D 字段时调用。所以观察到的行为是正确的。