Download Traits 4 User Manual
Transcript
Traits 4 User Manual, Release 4.5.0-rc.1 # event.py --- Example of trait event from traits.api import Event, HasTraits, List, Tuple point_2d = Tuple(0, 0) class Line2D(HasTraits): points = List(point_2d) line_color = RGBAColor(’black’) updated = Event def redraw(self): pass # Not implemented for this example def _points_changed(self): self.updated = True def _updated_fired(self): self.redraw() In support of the use of events, the Traits package understands attribute-specific notification handlers with names of the form _name_fired(), with signatures identical to the _name_changed() functions. In fact, the Traits package does not check whether the trait attributes that _name_fired() handlers are applied to are actually events. The function names are simply synonyms for programmer convenience. Similarly, a function named on_trait_event() can be used as a synonym for on_trait_change() for dynamic notification. Undefined Object Python defines a special, singleton object called None. The Traits package introduces an additional special, singleton object called Undefined. The Undefined object is used to indicate that a trait attribute has not yet had a value set (i.e., its value is undefined). Undefined is used instead of None, because None is often used for other meanings, such as that the value is not used. In particular, when a trait attribute is first assigned a value and its associated trait notification handlers are called, Undefined is passed as the value of the old parameter to each handler, to indicate that the attribute previously had no value. Similarly, the value of a trait event is always Undefined. 1.1.5 Deferring Trait Definitions One of the advanced capabilities of the Traits package is its support for trait attributes to defer their definition and value to another object than the one the attribute is defined on. This has many applications, especially in cases where objects are logically contained within other objects and may wish to inherit or derive some attributes from the object they are contained in or associated with. Deferring leverages the common “has-a” relationship between objects, rather than the “is-a” relationship that class inheritance provides. There are two ways that a trait attribute can defer to another object’s attribute: delegation and prototyping. In delegation, the deferring attribute is a complete reflection of the delegate attribute. Both the value and validation of the delegate attribute are used for the deferring attribute; changes to either one are reflected in both. In prototyping, the deferring attribute gets its value and validation from the prototype attribute, until the deferring attribute is explicitly changed. At that point, while the deferring attribute still uses the prototype’s validation, the link between the values is broken, and the two attributes can change independently. This is essentially a “copy on write” scheme. 20 Chapter 1. User Reference