Enthought Home home  |  www.enthought.com  |  www.scipy.org  |  installation
Enthought Projects


The following code example minimally illustrates the five primary features of the Traits package.

# all_traits_features.py

from enthought.traits.api import Delegate, HasTraits, Instance, Int, Str
import enthought.traits.ui

class Parent(HasTraits):

    # INITIALIZATION: last_name' is initialized to '':
    last_name = Str('')

class Child(HasTraits):
    age = Int

    # VALIDATION: 'father' must be a Parent instance:
    father = Instance(Parent)

    # DELEGATION: 'last_name' is delegated to father's 'last_name':
    last_name = Delegate('father')

    # NOTIFICATION: This method is called when 'age' changes:
    def _age_changed(self, old, new):
        print 'Age changed from %s to %s ' % (old, new)

# Set up the example:
joe = Parent()
joe.last_name = 'Johnson'
moe = Child()
moe.father = joe

# DELEGATION in action:
print "Moe's last name is %s" % moe.last_name

# NOTIFICATION in action:
moe.age = 10

# VISUALIZATION: Displays a UI for editing moe's
# attributes (if a supported GUI toolkit is installed)

The DELEGATION and NOTIFICATION segments in the above example yield the following command-line output: </p>

Moe's last name is Johnson
Age changed from 0 to 10</pre>

The configure_traits() command in the above example opens the following dialog box for editing the attributes of the Child instance:

traits example

Clicking <strong>Father</strong> on this dialog box opens an additional dialog box to modify the Parent instance:

traits example 2

Last updated: Tue 21 November 2017