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?
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.