property decorator and inheritance
Laurent
laurent.payot at gmail.com
Thu Nov 10 23:03:05 EST 2011
Hi. I couldn't find a way to overwrite a property declared using a decorator in a parent class. I can only do this if I use the "classic" property() method along with a getter function. Here's an example:
#!/usr/bin/python3
class Polite:
def __init__(self):
self._greeting = "Hello"
def get_greeting(self, suffix=", my dear."):
return self._greeting + suffix
greeting1 = property(get_greeting)
@property
def greeting2(self, suffix=", my dear."):
return self._greeting + suffix
class Rude(Polite):
@property
def greeting1(self):
return self.get_greeting(suffix=", stupid.")
@property
def greeting2(self):
return super().greeting2(suffix=", stupid.")
p = Polite()
r = Rude()
print("p.greeting1 =", p.greeting1)
print("p.greeting2 =", p.greeting2)
print("r.greeting1 =", r.greeting1)
print("r.greeting2 =", r.greeting2) # TypeError: 'str' object is not callable
In this example I can easily overwrite the greeting1 property. But the inherited greeting2 doesn't seem to be a property but a mere string.
I use a lot of properties decorators for simple properties in a project and I hate mixing them with a couple of "undecorated" properties that have to be overwritten in child classes. I tried using @greeting2.getter decorator and tricks like this but inheritance overwriting failed every time I used decorators.
Can someone tell me a way to use decorator-declared properties that can be overwritten in child classes?? That would be nice.
More information about the Python-list
mailing list