使用 super() 在 Child 中重新实现 Parent 的属性 setter
Reimplement Parent's attribute setter in Child using super()
我想在尝试为子 class 设置属性时提出一个 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
的属性 setter,而不是直接引用 Parent
?
您不能直接在 class
语句块的 top-level 处使用 super()
,因为此时 class
还不存在。
快速简单的解决方案是让您的 Parent
属性 setter 委托给另一个方法,即:
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
然后您只需在 child 类 中覆盖 _set(self)
,就像任何其他普通方法一样:
class Child(Parent):
def _set(self, value):
raise NotImplementedError
我想在尝试为子 class 设置属性时提出一个 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
的属性 setter,而不是直接引用 Parent
?
您不能直接在 class
语句块的 top-level 处使用 super()
,因为此时 class
还不存在。
快速简单的解决方案是让您的 Parent
属性 setter 委托给另一个方法,即:
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
然后您只需在 child 类 中覆盖 _set(self)
,就像任何其他普通方法一样:
class Child(Parent):
def _set(self, value):
raise NotImplementedError