3.2.1
Handler Decorator
The most flexible method of statically specifying that a
method is a notification handler for a trait is to use the @on_trait_change()
decorator. The @on_trait_change() decorator is more flexible than specially-named
method handlers, because it supports the very powerful extended trait name
syntax (see Section 3.1.2, “The name Parameter”). You can use the decorator to
set handlers on multiple attributes at once, on trait attributes of linked
objects, and on attributes that are selected based on trait metadata.
3.2.1.1
Decorator Syntax
The syntax for the decorator is:
@on_trait_change( 'extended_trait_name' )
def any_method_name( self, … ):
…
In this case, extended_trait_name
is a specifier for one or more trait attributes, using the syntax described in
Section 3.1.2, “The name Parameter”.
The signatures that are recognized for “decorated”
handlers are the same as those for dynamic notification handlers, as described
in Section 3.1. That is, they can have an object
parameter, because they can handle notifications for trait attributes that do
not belong to the same object.
3.2.1.2
Decorator Semantics
The functionality provided by the @on_trait_change()
decorator is identical to that of specially-named handlers, in that both result
in a call to on_trait_change() to register the method as a notification
handler. However, the two approaches differ in when
the call is made. Specially-named handlers are registered at class construction
time; decorated handers are registered at instance creation time, prior to
setting any object state.
A consequence of this difference is that the
@on_trait_change() decorator causes any default initializers for the traits it
references to be executed at instance construction time. In the case of
specially-named handlers, any default initializers are executed lazily.
|