4.1 DelegatesTo
The signature of the
DelegatesTo initializer is:
def __init__(self, delegate,
prefix='', listenable=True, **metadata)
The delegate parameter is a string that specifies the name
of an attribute on the same object, which refers to the object whose attribute
is deferred to; it is usually an Instance trait. The value of the delegating
attribute changes whenever:
·
The value of the appropriate attribute on the delegate object
changes.
·
The object referenced by the trait named in the delegate parameter changes.
·
The delegating attribute is explicitly changed.
Changes to the delegating attribute are propagated to the
delegate object’s attribute.
The prefix and listenable parameters to the initializer function
specify additional information about how to do the delegation.
If prefix is the empty
string or omitted, the delegation is to an attribute of the delegate object
with the same name as the trait defined by the DelegatesTo object. Consider the
following example:
# delegate.py --- Example of trait delegation
from enthought.traits.api \
import DelegatesTo, HasTraits, Instance, Str
class
Parent(HasTraits):
first_name = Str
last_name = Str
class Child(HasTraits):
first_name = Str
last_name = DelegatesTo('father')
father =
Instance(Parent)
mother = Instance(Parent)
"""
>>>
tony = Parent(first_name='Anthony', last_name='Jones')
>>>
alice = Parent(first_name='Alice', last_name='Smith')
>>>
sally = Child( first_name='Sally', father=tony, mother=alice)
>>>
print sally.last_name
Jones
>>>
sally.last_name = 'Cooper' # Updates delegatee
>>>
print tony.last_name
Cooper
>>>
sally.last_name = sally.mother # ERR: string expected
Traceback
(most recent call last):
File
"<stdin>", line 1, in ?
File
"c:\src\trunk\enthought\traits\trait_handlers.py", line
163, in
error
raise
TraitError, ( object, name, self.info(), value )
enthought.traits.trait_errors.TraitError:
The 'last_name' trait of a Child instance must be a value of type 'str', but a
value of <__main__.Parent object at 0x009DD6F0> was specified.
"""
A Child object delegates its last_name
attribute value to its father object’s last_name attribute. Because the prefix parameter was not specified in the Delegate
initializer, the attribute name on the delegatee is the same as the original
attribute name. Thus, the last_name of a
Child is the same as the last_name of its
father. When either the last_name of the
Child or the last_name of the father is
changed, both attributes reflect the new value.
|