科学计算三维可视化---Traits属性的监听
Traits属性的监听
HasTraits对象所有Traits属性都自动支持监听功能,当每个Traits属性发生变化时,HasTraits对象会通知监听此属性的函数
两种监听模式
静态监听
动态监听
from traits.api import HasTraits,Int,Str class Child(HasTraits): name = Str age = Int doing = Str def __str__(self): return "%s<%x>"%(self.name,id(self)) #静态监听age属性的变化 def _age_changed(self,old,new): print("%s.age change: from %s to %s"%(self,old,new)) # 静态监听任何Trait属性的变化 def _anytrait_changed(self, name, old, new): print("anytrait change:%s.%s from %s to %s" % (self,name, old, new)) #用于动态监测属性变化 def log_trait_changed(obj,name,old,new): print("log: %s.%s change: from %s to %s" % (obj, name, old, new))
z = Child(name="ZhangSan",age=4) l = Child(name="Lisi",age=1) #动态监听doing属性的变化 z.on_trait_change(log_trait_changed,name="doing")
anytrait change:<a2f1360>.age from 0 to 4 #先监听所有 <a2f1360>.age change: from 0 to 4 #再监听自定义 anytrait change:ZhangSan<a2f1360>.name from to ZhangSan
anytrait change:<a2f13b8>.age from 0 to 1 <a2f13b8>.age change: from 0 to 1 anytrait change:Lisi<a2f13b8>.name from to Lisi
上面是静态监听,下面看动态监听:(都会调用_anytrait_changed,再根据我们定义的监听方法选择)
>>> z.age = 5 #静态监听 anytrait change:ZhangSan<a2f1360>.age from 4 to 5 ZhangSan<a2f1360>.age change: from 4 to 5 >>> z.doing = "playing" #动态监听 anytrait change:ZhangSan<a2f1360>.doing from to playing log: ZhangSan<a2f1360>.doing change: from to playing
>>> l.doing = "see" #由于没有设置关联的监听方法,所以只会调用_anytrait_changed
anytrait change:Lisi<a2f13b8>.doing from to see
将一个Traits变量绑定静态动态监听后的顺序(先执行_anytrait_changed,后静态,再动态)
>>> z.on_trait_change(log_trait_changed,name="age") >>> z.age = 3 anytrait change:ZhangSan<a2f1360>.age from 5 to 3 ZhangSan<a2f1360>.age change: from 5 to 3 log: ZhangSan<a2f1360>.age change: from 5 to 3
当我们相对多个Traits属性都使用同一个监听函数时:
我们可以使用一种修饰函数@on_trait_change(names) #names可以是字符串或者列表,表示一串traits信息
实现on_trait_change方法使用
class Child(HasTraits): name = Str age = Int doing = Str def __str__(self): return "%s<%x>"%(self.name,id(self)) #静态监听age属性的变化 def _age_changed(self,old,new): print("%s.age change: from %s to %s"%(self,old,new)) @on_trait_change(["name","age"]) #注意列表中是字符串 def age_and_name_changed(self,name,old,new): print("custom change:%s.%s from %s to %s" % (self,name, old, new)) # 静态监听任何Trait属性的变化 def _anytrait_changed(self, name, old, new): print("anytrait change:%s.%s from %s to %s" % (self,name, old, new))
修改某一变量:查看执行顺序
z = Child(name="ZhangSan",age=4) # l = Child(name="Lisi",age=1) # #动态监听doing属性的变化 z.on_trait_change(log_trait_changed,name="age") z.age = 10
anytrait change:ZhangSan<a64eb48>.age from 4 to 10 #先是_anytrait_changed ZhangSan<a64eb48>.age change: from 4 to 10 #然后是静态 custom change:ZhangSan<a64eb48>.ZhangSan<a64eb48> from age to 10 #再自定义 log: ZhangSan<a64eb48>.age change: from 4 to 10 #最后是动态