【问题标题】:Overwrite base class attribute with @property of the same name用同名的@property 覆盖基类属性
【发布时间】:2015-09-30 08:04:00
【问题描述】:

我正在尝试对 python 类进行子类化并使用 @property 函数覆盖常规属性。问题是我无法修改父类,子类的 api 需要看起来与父类相同(但行为不同)。 (所以我的问题与this one 不同,this one 的父类也使用了@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。你读过关于属性的the documentation 吗?但是,我认为您尝试的方法不起作用,因为 self.attr 存储在实例上,而不是类上,因此以您似乎尝试的方式使用 super 无济于事。

标签: python properties subclass


【解决方案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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-07-05
    • 2019-10-13
    • 2018-08-31
    • 1970-01-01
    • 1970-01-01
    • 2018-12-10
    • 1970-01-01
    相关资源
    最近更新 更多