问题
Given,
from enthought.traits.api import HasTraits, Tuple, Delegate, Trait, Float,Dict,List
class Foo(HasTraits):
def __init__(self):
super(Foo,self).__init__()
self.add_trait('node',List)
def _node_items_changed(self,name,old,new):
print name
print old
print new
Why do I get:
>>> f = Foo()
>>> f.node.append(0)
node_items
<undefined>
<traits.trait_handlers.TraitListEvent object at 0x05BA8CF0>
The documentation says I should get a list of items added/removed.
What am I missing here? This is traits 4.3 on windows 8.
Thanks!
回答1:
There seems to be a distinction between changing the value of the collection as a whole (the List
) and changing a member within the collection. Appending appears to change a member within (or at least results in the same notification). If you change the value of the container as a whole, you do indeed get the changed list as the new
value:
from enthought.traits.api import HasTraits, Tuple, Delegate, Trait, Float,Dict,List
class Foo(HasTraits):
def __init__(self):
super(Foo,self).__init__()
self.add_trait('node',List)
def _node_changed(self,name,old,new):
print("_node_changed: %s %s %s" % (name, str(old), str(new)))
def _node_items_changed(self,name,old,new):
print("_node_items_changed: %s %s %s" % (name, str(old), str(new)))
f = Foo()
# change the List membership with append:
f.node.append(0)
# _node_items_changed: node_items <undefined> <traits.trait_handlers.TraitListEvent object at 0x10128af50>
# change the List itself:
f.node = [1,2,3]
# _node_changed: node [0] [1, 2, 3]
# change a member (same result as append):
f.node[1] = 4
# _node_items_changed: node_items <undefined> <traits.trait_handlers.TraitListEvent object at 0x10128af50>
There's more info here, if you haven't seen this section already. See this answer too.
来源:https://stackoverflow.com/questions/19041426/traits-list-not-reporting-items-added-or-removed