我想从包含属性x
的类继承,然后通过重写setter将此属性设置为子类中的只读属性。如果父类中的__init__
使用原始设置器,则这不起作用。考虑下面的代码。Python:重写属性时发生意外的行为
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
二传手被调用,而不是x
二传手Parent
。我怎样才能以Python方式使用Parent
的setter?
需要明确的是,当self.x = ...
出现在Parent
的方法,它应该总是利用x
二传手在Parent
,当self.x = ...
出现在Child
的方法,它应该总是利用x
二传手在Child
,从而引发异常。
你不能继承这样的属性,你可以这样做:'Child.x = Parent.x.setter(Parent.x.fset)'类初始化后。 –
@AshwiniChaudhary这是行不通的。它不会为'Child'使'x'只读。 –