oop - Python overriding getter without setter -


class human(object):     def __init__(self, name=''):         self.name = name      @property     def name(self):         return self._name      @name.setter     def name(self, value):         self._name = value  class superhuman(human):     @property     def name(self):         return 'super ' + name  s = superhuman('john') print s.name  # doesn't work :( "attributeerror: can't set attribute" s.name = 'jack' print s.name 

i want able override property able use super parent's setter without having override setter in child class.

is pythonicaly possible?

use just .getter decorator of original property:

class superhuman(human):     @human.name.getter     def name(self):         return 'super ' + self._name 

note have use full name reach original property descriptor on parent class.

demonstration:

>>> class superhuman(human): ...     @human.name.getter ...     def name(self): ...         return 'super ' + self._name ...  >>> s = superhuman('john') >>> print s.name super john >>> s.name = 'jack' >>> print s.name super jack 

the property descriptor object one object, though can have multiple methods associated (the getter, setter , deleter). .getter, .setter , .deleter decorator functions provided existing property descriptor return copy of descriptor itself, 1 specific method replaced.

so in human base class happens first create descriptor @property decorator, replace descriptor 1 has both getter , setter @name.setter syntax. works because python decorators replace original decorated function same name, executes name = name.setter(name). see how @property decorator work? details on how works.

in subclass use trick create new copy of descriptor getter replaced.


Comments

Popular posts from this blog

javascript - Slick Slider width recalculation -

jsf - PrimeFaces Datatable - What is f:facet actually doing? -

angular2 services - Angular 2 RC 4 Http post not firing -