Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<pre><code>from enthought.traits.api import HasStrictTraits, Instance, Property class ExternalModel(object): foo = 'foo' class TraitsModel(HasStrictTraits): _e = Instance(ExternalModel, ExternalModel()) def __init__(self): ''' &gt;&gt;&gt; wrapper = TraitsModel() &gt;&gt;&gt; wrapper.foo 'foo' &gt;&gt;&gt; wrapper._e.foo = 'bar' &gt;&gt;&gt; wrapper.foo 'bar' &gt;&gt;&gt; wrapper.trait_names() ['trait_added', '_e', 'foo', 'trait_modified'] ''' HasStrictTraits.__init__(self) for trait in (name for name in dir(self._e) if not name.startswith('__')): self.__class__.add_class_trait( trait, Property( lambda:getattr(self._e, trait), lambda attr:setattr(self._e, trait, attr) ) ) if __name__ == '__main__': import doctest doctest.testmod() </code></pre> <p>A fairly robust solution is to use the <a href="http://www.cs.nott.ac.uk/~jvb/ETS34_API/enthought.traits.has_traits.HasTraits.html#_add_class_trait" rel="nofollow"><code>add_class_trait</code></a> of the <code>HasTraits</code> class, coupled with <code>dir(self._e)</code> to get the names of the <em>class</em> attributes of <code>ExternalModel</code> and a generator expression/list comprehension to filter the magic class method names (<code>filter</code> with an appropriate function would work better for wrapping a more complex class).</p> <p>Also:</p> <ul> <li><p><code>ExternalModel</code> should inherit from <code>object</code></p></li> <li><p><code>__init__</code> should call <code>HasStrictTraits.__init__</code> (or <code>super(HasStrictTraits, self).__init__()</code>)</p></li> <li><p><code>_e</code> can also be created in the Instance trait declaration as the second argument using <code>ExternalModel()</code> or even <code>()</code>, or as a method of TraitsModel like:</p> <pre><code>def __e_default(self): # note preceding underscore return ExternalModel() </code></pre></li> </ul> <p>Lastly, I have an <a href="http://www.cs.nott.ac.uk/~jvb/ETS34_API/enthought.html" rel="nofollow">slightly old copy of the Enthought APIs including Traits</a> which can be very handy.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload