Python 重新实施母公司';使用super()在子级中设置属性setter

Python 重新实施母公司';使用super()在子级中设置属性setter,python,python-3.x,super,Python,Python 3.x,Super,当试图在子类中设置属性时,我想提出一个NotImplementedError。代码如下: class Parent(): def __init__(self): self._attribute = 1 @property def attribute(self): return self._attribute @attribute.setter def attribute(self, value): se

当试图在子类中设置属性时,我想提出一个
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()
,而不是直接引用
Parent
,来重新实现
Child
的属性设置器?

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

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

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
然后您只需在子类中重写
\u set(self)
,就像其他普通方法一样:

class Child(Parent):
    def _set(self, value):
        raise NotImplementedError
您不能直接在
class
语句块的顶层使用
super()
,因为此时
class
还不存在

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

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
然后您只需在子类中重写
\u set(self)
,就像其他普通方法一样:

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