【问题标题】:Reimplement Parent's attribute setter in Child using super()使用 super() 在 Child 中重新实现 Parent 的属性设置器
【发布时间】:2018-08-16 09:49:48
【问题描述】:

我想在尝试在子类中设置属性时提出NotImplementedError。代码如下:

class Parent():

    def __init__(self):
        self._attribute = 1

    @property
    def attribute(self):
        return self._attribute

    @attribute.setter
    def attribute(self, value):
        self._attribute = value


class Child(Parent):

    @Parent.attribute.setter
    def attribute(self, value):
        raise NotImplementedError('Not implemented.')

有没有办法使用super() 重新实现Child 的属性设置器,而不是直接引用Parent

【问题讨论】:

    标签: python python-3.x super


    【解决方案1】:

    您不能直接在class 语句块的顶层使用super(),因为此时class 还不存在。

    快速简单的解决方案是让您的Parent 属性设置器委托给另一个方法,即:

    class Parent():
        def __init__(self):
            # note that you can use the property here,
            # no need to break encapsulation.
            self.attribute = 1
    
        @property
        def attribute(self):
            return self._attribute
    
        @attribute.setter
        def attribute(self, value):
            self._set(value) 
    
        def _set(self, value):
            self._attribute = value
    

    然后你只需要在你的子类中重写_set(self),就像任何其他普通方法一样:

    class Child(Parent):
        def _set(self, value):
            raise NotImplementedError
    

    【讨论】:

      猜你喜欢
      • 2017-06-17
      • 2020-04-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-06
      • 2011-06-16
      • 2014-04-13
      • 1970-01-01
      相关资源
      最近更新 更多