2015-07-11 68 views
2

我想要继承一个python类,并用@property函数覆盖常规属性。问题在于我无法修改父类,并且子类的api需要看起来与父类相同(但行为不同)。 (我的问题是从this one其中父类也使用@property方法来访问基础属性不同。)用@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 

希望很清楚我想要做什么以及为什么。但我无法弄清楚如何。

+0

你需要写你的属性的设置,以及固定的。你有没有阅读[文档](https://docs.python.org/2/library/functions.html#property)属性?然而,我不认为你正在尝试的是什么会起作用,因为'self.attr'存储在实例中,而不是类,所以按照你似乎正在尝试的方式使用'super'将无济于事。 – BrenBarn

回答

1

这是很容易通过添加一个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