property decorator and inheritance
alex23
wuwei23 at gmail.com
Thu Nov 10 23:43:30 EST 2011
On Nov 11, 2:03 pm, Laurent <laurent.pa... at gmail.com> wrote:
> Hi. I couldn't find a way to overwrite a property declared using a decorator in a parent class.
> class Polite:
> @property
> def greeting2(self, suffix=", my dear."):
> return self._greeting + suffix
Here you set up greeting2 as a property.
> class Rude(Polite):
> @property
> def greeting2(self):
> return super().greeting2(suffix=", stupid.")
Here you call Polite.greeting2 as a function.
> print("r.greeting2 =", r.greeting2) # TypeError: 'str' object is not callable
And here it's telling you that you're trying to treat a string - the
output of Polite.greeting2 - as a function.
The problem isn't that you cannot override greeting2 on Rude, it's
that you can't treat properties as functions, so you can't pass in a
new suffix. Instead, break the suffix out as a class attribute, then
each descendent just needs to override that attribute:
class Polite(object):
suffix = ', my dear'
@property
def greeting(self):
return 'Hello' + self.suffix
class Rude(Polite):
suffix = ', stupid'
More information about the Python-list
mailing list