简体   繁体   English

python3:覆盖属性的setter

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM