[英]Overwrite base class attribute with @property of the same name
我試圖子類化一個python類並用@property函數覆蓋一個常規屬性。 問題是我不能修改父類,子類的api需要看起來與父類相同(但行為不同)。 (我的問題是從不同的這一個 ,其中父類也使用@property方法來訪問基礎屬性。)
最簡單的例子是
# assume this class can't be overwritten
class Parent(object):
def __init__(self, a):
self.attr = a
# how do I make this work?
class Child(Parent):
def __init__(self, a):
super(Child, self).__init__(a)
# overwrite access to attr with a function
@property
def attr(self):
return super(Child, self).attr**2
c = Child(4)
print c.attr # should be 16
調用父init方法時會產生錯誤。
<ipython-input-15-356fb0400868> in __init__(self, a)
2 class Parent(object):
3 def __init__(self, a):
----> 4 self.attr = a
5
6 # how do I make this work?
AttributeError: can't set attribute
希望很清楚我想做什么以及為什么。 但我無法弄清楚如何。
通過添加setter方法可以很容易地解決這個問題
class Child(Parent):
def __init__(self, a):
self._attr = None
super(Child, self).__init__(a)
# overwrite access to a with a function
@property
def attr(self):
return self._attr**2
@attr.setter
def attr(self, value):
self._attr = value
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.