3.2.2
Specially-named Notification Handlers
There are two kinds of special method names that can be
used for static trait attribute change notifications. One is
attribute-specific, and the other applies to all trait attributes on a class.
To notify about changes to a single trait attribute named name, define a method named _name_changed() or _name_fired().
The leading underscore indicates that attribute-specific notification handlers
are normally part of a class´s private API. Methods named _name_fired() are normally used with traits that are
events, described in Section 3.3, “Trait Events”.
To notify about changes to any trait attribute on a class,
define a method named _anytrait_changed().
Both of these types of static trait attribute notification
methods are illustrated in the following example:
# static_notification.py --- Example of static attribute
# notification
from
enthought.traits.api import HasTraits, Float
class
Person(HasTraits):
weight_kg = Float(0.0)
height_m
= Float(1.0)
bmi =
Float(0.0)
def _weight_kg_changed(self, old, new):
print 'weight_kg changed from %s to %s ' % (old, new)
if self.height_m != 0.0:
self.bmi
= self.weight_kg / (self.height_m**2)
def
_anytrait_changed(self, name, old, new):
print 'The %s trait changed from %s to %s ' \
% (name, old, new)
"""
>>>
bob = Person()
>>>
bob.height_m = 1.75
The height_m
trait changed from 1.0 to 1.75
>>>
bob.weight_kg = 100.0
The
weight_kg trait changed from 0.0 to 100.0
weight_kg
changed from 0.0 to 100.0
The bmi
trait changed from 0.0 to 32.6530612245
"""
In this example, the attribute-specific notification
function is _weight_kg_changed(), which is called only when the weight_kg attribute changes. The class-specific
notification handler is _anytrait_changed(), and is called when weight_kg, height_m,
or bmi changes. Thus, both handlers are
called when the weight_kg attribute
changes. Also, the _weight_kg_changed() function modifies the bmi attribute, which causes _anytrait_changed()
to be called for that attribute.
The arguments that are passed to the trait attribute
change notification method depend on the method signature and on which type of
static notification handler it is.
|