I have a base class with a property which (the get method) I want to overwrite in the subclass. My first thought was something like:
class Foo(object): def _get_age(self): return 11 age = property(_get_age) class Bar(Foo): def _get_age(self): return 44
This does not work (subclass bar.age returns 11). I found a solution with an lambda expression which works:
age = property(lambda self: self._get_age())
So is this the right solution for using properties and overwrite them in a subclass, or are there other preferred ways to do this?
I simply prefer to repeat the
property()as well as you will repeat the@classmethoddecorator when overriding a class method.While this seems very verbose, at least for Python standards, you may notice:
1) for read only properties,
propertycan be used as a decorator:2) in Python 2.6, properties grew a pair of methods
setteranddeleterwhich can be used to apply to general properties the shortcut already available for read-only ones: