简体   繁体   English

检查同步特征:特质/特质UI

[英]Inspect for synchronized traits: Traits/TraitsUI

I'm sweeping through all the Traits in a large program, and many of our traits are synchronized. 我正在大型程序中遍历所有特征,并且我们的许多特征是同步的。 For example, consider HasTrait objects of the structure: 例如,考虑结构的HasTrait对象:

a = Material1.ShellMaterial
b = Material2.CoreMaterial
c = Material3.MaterialX

In our application, it turns out that a and c are synchronized traits. 在我们的应用程序中,事实证明a和c是同步特征。 In other words, Material3.MaterialX is the same as Material1.ShellMaterial , and they have set using sync_trait() (HasTraits API) . 换句话说, Material3.MaterialXMaterial1.ShellMaterial相同,它们使用sync_trait() (HasTraits API)进行设置

Is it possible to inspect a,b,c and dynamically determine that a and c are synchronized? 是否可以检查a,b,c并动态确定a和c已同步?

The goal is to plot all of these, but hide redundant plots from the user. 目标是绘制所有这些图,但向用户隐藏多余的图。 Typical comparisons between these like a==c return False , despite these objects representing the same data. 尽管这些对象表示相同的数据,但它们之间的典型比较(例如a==c返回False

As far as I know there is no official API that allows to inspect the synchronization state of traits. 据我所知,没有官方的API可以检查特征的同步状态。

Of course, you could simply call the sync_trait() method again to make sure that the traits are synchronized (or not synchronized, if you use remove=True ). 当然,您可以再次简单地再次调用sync_trait()方法,以确保特征已同步(如果使用remove=True ,则不同步)。 As a result, you will know the synchronization state of the traits. 结果,您将知道特征的同步状态。

If you do not want to change the synchronization state, you have to rely on non-official API functions, which are not documented and possibly subject to change -- so use them at your own risk. 如果您不想更改同步状态,则必须依靠非官方的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>

Again, use at your own risk, but it works for me. 同样,使用后果自负,但对我有用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM