给定基于特征的类 Material-class、Base-class 和 Child-class(从 Base-class 派生),如果 Child-class 的 Property-trait b
则运行以下代码只依赖于 a
或 x
属性,即
b = 属性(Float, dependent_on=['a'])
或
b = 属性(Float, dependent_on=['x'])
但如果它取决于两者,则不然:
b = 属性(Float, dependent_on=['a','x'])
为什么?
from traits.api import HasTraits, DelegatesTo, Float, Instance, Range, Property
class Material(HasTraits):
a = Float(10)
class Base(HasTraits):
x = Float(-1)
class Child(Base):
m = Instance(Material)
a = DelegatesTo('m')
# b = Property(Float, depends_on=['a']) # <-- runs
# b = Property(Float, depends_on=['x']) # <-- runs
b = Property(Float, depends_on=['a','x']) # <-- fails
def _get_b(self):
return self.a * self.x
c = Child(m=Material())
最佳答案
您可以通过不使用 DelegatesTo
并仅监听 m.a
上的更改来解决此问题:
class Child(Base):
m = Instance(Material)
b = Property(Float, depends_on=['m.a','x']) # <-- runs
def _get_b(self):
return self.a * self.x
委托(delegate)的问题似乎与设置监听器有关。我收到的错误消息是
DelegationError:“Child”对象的“a”属性具有一个没有特征的委托(delegate)。
。
关于python - 具有 "depends_on"的属性特征,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27444786/