[英]python3: overriding setter of a property
class Base:
def __init__(self):
self._prop = None
pass
def get_prop(self):
print('base get prop')
return self._prop
def set_prop(self, prop):
print('base set prop')
self._prop = prop
prop = property(get_prop, set_prop)
pass
class Derived(Base):
def set_prop(self, prop):
print('Derived set prop')
self._prop = prop
pass
base = Base()
base.prop = 1
print(base.prop)
derive = Derived()
derive.prop = 1
print(derive.prop)
result: 结果:
base set prop
base get prop
1
base set prop
base get prop
1
Expecting to get Derived set prop
since I override it in the derived class. 由于我在派生类中重写了它,因此期望获得
Derived set prop
。
When I googled it, I saw annotating with @Base.prop.setter
. 当我用
@Base.prop.setter
搜索时,我看到了@Base.prop.setter
注释。 I tried that as well, but that didn't work. 我也尝试过,但是没有用。 I think it's because how they create the
Base
's prop
is different. 我认为这是因为他们创建
Base
prop
方式不同。
But I cannot easily update the Base
class in this situation. 但是在这种情况下,我无法轻松更新
Base
类。
One way is to completely re-implement prop
in the Derive
class, but I know it's not the right way. 一种方法是在
Derive
类中完全重新实现prop
,但我知道这不是正确的方法。 Is there another way? 还有另一种方法吗?
This is because when you assign to Base.prop
with property(get_prop, set_prop)
, this property
object is instantiated with the set_prop
function object as defined in the Base
class. 这是因为当您使用
property(get_prop, set_prop)
分配给Base.prop
时,此property
对象将使用Base
类中定义的set_prop
函数对象实例化。 The fact that the Derived
class inherits the Base
class does not magically update the reference to the Base.set_prop
method within the property
object. Derived
类继承Base
类的事实并不能神奇地更新对property
对象中Base.set_prop
方法的引用。
You can either define another prop
inside the Derived
class: 您可以在
Derived
类中定义另一个prop
:
class Derived(Base):
def set_prop(self, prop):
print('Derived set prop')
self._prop = prop
prop = property(Base.get_prop, set_prop)
or you can simply use property
as a decorator: 或者您可以简单地使用
property
作为装饰器:
class Base:
def __init__(self):
self._prop = None
pass
@property
def prop(self):
print('base get prop')
return self._prop
@prop.setter
def prop(self, prop):
print('base set prop')
self._prop = prop
class Derived(Base):
@Base.prop.setter
def prop(self, prop):
print('Derived set prop')
self._prop = prop
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.