我想从包含属性x
的类继承,然后通过重写setter使这个属性在子类中成为只读的。如果父类中的__init__
使用原始setter,则这不起作用。考虑以下代码。你知道吗
class Parent:
def __init__(self, x=1):
# I want the following line to use the setter defined in the Parent
# class, even when __init__ is called from Child using super.
self.x = x
# Other initialization of Parent goes here.
@property
def x(self):
return self._x
@x.setter
def x(self, value):
"""Check that x is non-negative."""
if value < 0:
raise ValueError("x must be non-negative.")
self._x = value
class Child(Parent):
def __init__(self):
super().__init__() # Need this for initialization.
@property
def y(self):
return self._y
@y.setter
def y(self, value):
"""x can only be written to implicitly by setting y."""
self._y = value
self._x = abs(value)
@property
def x(self):
return self._x
@x.setter
def x(self, value):
raise AttributeError("Illegal access to x")
如果我现在尝试实例化Child
,我会得到AttributeError: Illegal access to x
,因为当调用行self.x = x
时,会调用Child
的x
setter,而不是Parent
的x
setter。我怎样才能让它以Pythonic的方式使用Parent
的setter呢?你知道吗
要清楚的是,当self.x = ...
出现在Parent
的方法中时,它应该始终使用Parent
中的x
setter,当self.x = ...
出现在Child
的方法中时,它应该始终使用Child
中的x
setter,从而引发异常。你知道吗
你知道吗 我设法通过调换工作自己解决了这个问题
在
Parent.__init__
中我也可以摆脱
在
Child
if中,我使用@Parent.x.setter
,而不是@x.setter
。你知道吗相关问题 更多 >
编程相关推荐