I’m currently using the @property
decorator to achieve “getters and setters” in a couple of my classes. I wish to be able to inherit these @property
methods in a child class.
I have some Python code (specifically, I’m working in py3k) which looks vaguely like so:
class A:
@property
def attr(self):
try:
return self._attr
except AttributeError:
return ''
class B(A):
@property
def attr(self):
return A.attr # The bit that doesn't work.
@attr.setter
def attr(self, value):
self._attr = value
if __name__ == '__main__':
b = B()
print('Before set:', repr(b.attr))
b.attr = 'abc'
print(' After set:', repr(b.attr))
I have marked the part that doesn’t work with a comment. I want the base class’ attr getter to be returned. A.attr
returns a property object (which is probably very close to what I need!).
Edit:
After receiving the answer below from Ned I thought up what I think is a more elegant solution to this problem.
class A:
@property
def attr(self):
try:
return self._attr
except AttributeError:
return ''
class B(A):
@A.attr.setter
def attr(self, value):
self._attr = value
if __name__ == '__main__':
b = B()
print('Before set:', repr(b.attr))
b.attr = 'abc'
print(' After set:', repr(b.attr))
The .setter
decorator expects a property object which we can get using @A.attr
. This means we do not have to declare the property again in the child class.
(This is the difference between working on a problem at the end of the day vs working on it at the beginning of the day!)
question from:
https://stackoverflow.com/questions/3336767/overriding-inherited-properties-getters-and-setters-in-python 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…