Setting up a dynamic trait attribute change notification
handler is illustrated in the following example:
# dynamic_notification.py --- Example of dynamic notification
from
enthought.traits.api import Float, HasTraits, Instance
class Part
(HasTraits):
cost =
Float(0.0)
class Widget (HasTraits):
part1 = Instance(Part)
part2 = Instance(Part)
cost =
Float(0.0)
def
__init__(self):
self.part1 = Part()
self.part2 = Part()
self.part1.on_trait_change(self.update_cost, 'cost')
self.part2.on_trait_change(self.update_cost, 'cost')
def
update_cost(self):
self.cost = self.part1.cost + self.part2.cost
# Example:
w = Widget()
w.part1.cost
= 2.25
w.part2.cost
= 5.31
print w.cost
# Result:
7.56
In this example, the Widget constructor sets up a dynamic
trait attribute change notification so that its update_cost() method is called
whenever the cost attribute of either its part1 or part2
attribute is modified. This method then updates the cost attribute of the widget object.