我在一个大型程序中扫描所有的特征,我们的许多特征是同步的。例如,考虑结构的HasTrait对象:
a = Material1.ShellMaterial
b = Material2.CoreMaterial
c = Material3.MaterialX在我们的应用程序中,a和c是同步的特征。换句话说,Material3.MaterialX和Material1.ShellMaterial是一样的,他们使用sync_trait() (HasTraits API)进行设置。
可以检查a、b、c并动态确定a和c是同步的吗?
其目标是绘制所有这些,但对用户隐藏冗余的情节。尽管这些对象表示相同的数据,但它们之间的典型比较,如a==c返回False。
发布于 2016-02-19 09:47:54
据我所知,没有官方API允许检查特征的同步状态。
当然,您可以简单地再次调用sync_trait()方法来确保这些特征是同步的(如果使用remove=True,则不是同步的)。因此,您将知道这些特征的同步状态。
如果您不想更改同步状态,则必须依赖非官方API函数,这些函数没有文档化,而且可能会发生更改--因此,使用它们需要您自己承担风险。
from traits.api import HasTraits, Float
class AA(HasTraits):
a =Float()
class BB(HasTraits):
b = Float()
aa = AA()
bb = BB()
aa.sync_trait("a", bb, "b")
# aa.a and bb.b are synchronized
# Now we use non-official API functions
info = aa._get_sync_trait_info()
synced = info.has_key("a") # True if aa.a is synchronized to some other trait
if synced:
sync_info = info["a"] # fails if a is not a synchronized trait
# sync_info is a dictionary which maps (id(bb),"b") to a tuple (wr, "b")
# If you do not know the id() of the HasTraits-object and the name of
# the trait, you have to loop through all elements of sync_info and
# search for the entry you want...
wr, name = sync_info[(id(bb), "b")]
# wr is a weakref to the class of bb, and name is the name
# of the trait which aa.a is synced to
cls = wr() # <__main__.BB at 0x6923a98>再说一次,你自己用,但对我有用。
https://stackoverflow.com/questions/28146253
复制相似问题