HasTraits overiding inherited getter/setter methods

191 views Asked by At

I would like to mix a HasTraits with a standard python object using multiple inheritance. When i do this, the getter/setter methods of the standard object dont function as expected. The example below demonstrates this.

from traits.api import HasTraits


class A(object):
    @property
    def name(self):
        print 'getter'
        try:
            return self._name
        except(AttributeError):
            return 'nobody'

    @name.setter
    def name(self, val):
        print 'setter'
        self._name = val.upper()

class B(A, HasTraits):
    pass


b = B()
b.name  #calls getter 

b.name = 'name' # doesnt call setter
b.name # doesnt call getter

I assume this is because the HasTraits class intercepts the standard get/set methods. Is there a way around this?

1

There are 1 answers

0
aestrivex On

I'm pretty sure there is not a way to make traits play nicely with the native python decorator @property. At least, not any reasonably clean way.

However traits has its own Property concept with getters and setters. You can define a Property trait which does what you want as a simple getter/setter.

class B(A, HasTraits):
    this_name = Property
    def _get_this_name(self):
      return self.name
    def _set_this_name(self, value):
      self.name = value

And if you subclass a HasTraits which contains a Property, that traits-specific getter/setter effects will be preserved in the subclass. So there is no reason -- that is if you already want the type-checking of traits in your program -- to use the @property decorator and not the Property getter in the first place.