I have defined a property area and its getter in a parent class Shape. In a child class Square I would like to expand the getter functionality of area. I wrote something which doesn't work:
version 1
class Shape:
def __init__(self):
self._area = None
@property
def area(self):
print('hello parent')
return self._area
# setter of `area` could be also defined here; hence in the child
# I would like to keep `area`, only decorating its getter.
class Square(Shape):
def __init__(self):
super(Square, self).__init__()
area = Shape.area.getter(self.dosomething())
def dosomething(self):
def new_func():
print('hello child')
Shape.area.fget(self)
return new_func
sq = Square()
When I run the code, I don't get the 'hello child':
>>> sq.area
hello parent
There are some obvious problems with my code above. For example, in Square I should have
self.area = Shape.area.getter(self.dosomething())
rather than no self. Then I would need to define the setter of area in parent...
version 2
After some fiddling, I came up with the following code,
class Shape:
def __init__(self):
self._area = None
@property
def area(self):
print('hello parent')
return self._area
class Square(Shape):
def __init__(self):
super(Square, self).__init__()
@Shape.area.getter
def area(self):
print('hello child')
Shape.area.fget(self)
sq = Square()
This time, it seems to do what I want:
>>> sq.area
hello child
hello parent
However, my ide tells me the line def area(self): in Square "overrides method in Shape".
Furthermore, IDE also says in Shape.area.fget(self), self is an unexpected argument. Even though the code runs without error.
It feels like version 2 is a hack. Why is my ide complaining? I thought in version 2 I did not define a brand-new area, just decorating the inherited area's fget, no?