【发布时间】:2021-11-04 19:43:12
【问题描述】:
我在父类Shape 中定义了一个属性area 及其getter。在子类Square 中,我想扩展area 的getter 功能。我写了一些不起作用的东西:
版本 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()
当我运行代码时,我没有得到“你好孩子”:
>>> sq.area
hello parent
我上面的代码有一些明显的问题。例如,Square 我应该有
self.area = Shape.area.getter(self.dosomething())
而不是没有self。然后我需要在父级中定义area 的setter...
版本 2
经过一番折腾,我想出了以下代码,
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()
这一次,它似乎如愿以偿:
>>> sq.area
hello child
hello parent
但是,我的 ide 告诉我 def area(self): 中的 Square 行“覆盖 Shape 中的方法”。
此外,IDE 在Shape.area.fget(self) 中还说,self 是一个意外参数。即使代码运行没有错误。
感觉第 2 版是一个 hack。为什么我的ide在抱怨?我以为在第2版我并没有定义一个全新的area,只是装饰了继承的area的fget,不是吗?
【问题讨论】:
标签: python properties decorator