在 Python 中覆盖继承属性的 getter 和 setter [英] Overriding inherited properties’ getters and setters in Python

查看:38
本文介绍了在 Python 中覆盖继承属性的 getter 和 setter的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在使用 @property 装饰器在我的几个类中实现getter 和 setter".我希望能够在子类中继承这些 @property 方法.

I’m currently using the @property decorator to achieve "getters and setters" in a couple of my classes. I wish to be able to inherit these @property methods in a child class.

我有一些 Python 代码(具体来说,我在 py3k 中工作)看起来像这样:

I have some Python code (specifically, I’m working in py3k) which looks vaguely like so:

class A:
    @property
    def attr(self):
        try:
            return self._attr
        except AttributeError:
            return ''

class B(A):
    @property
    def attr(self):
        return A.attr   # The bit that doesn't work.

    @attr.setter
    def attr(self, value):
        self._attr = value

if __name__ == '__main__':
    b = B()
    print('Before set:', repr(b.attr))
    b.attr = 'abc'
    print(' After set:', repr(b.attr))

我用注释标记了不起作用的部分.我希望返回基类的 attr getter.A.attr 返回一个属性对象(这可能与我需要的非常接近!).

I have marked the part that doesn’t work with a comment. I want the base class’ attr getter to be returned. A.attr returns a property object (which is probably very close to what I need!).

编辑:
在收到 Ned 的回答后,我想到了我认为更优雅的解决方案.

Edit:
After receiving the answer below from Ned I thought up what I think is a more elegant solution to this problem.

class A:
    @property
    def attr(self):
        try:
            return self._attr
        except AttributeError:
            return ''

class B(A):        
    @A.attr.setter
    def attr(self, value):
        self._attr = value

if __name__ == '__main__':
    b = B()
    print('Before set:', repr(b.attr))
    b.attr = 'abc'
    print(' After set:', repr(b.attr))

.setter 装饰器需要一个我们可以使用 @A.attr 获得的属性对象.这意味着我们不必在子类中再次声明该属性.

The .setter decorator expects a property object which we can get using @A.attr. This means we do not have to declare the property again in the child class.

(这是一天结束时解决问题与一天开始时解决问题的区别!)

(This is the difference between working on a problem at the end of the day vs working on it at the beginning of the day!)

推荐答案

我想你想要:

class B(A):
    @property
    def attr(self):
        return super(B, self).attr

您提到想要返回父类的 getter,但您需要调用 getter,而不是返回它.

You mention wanting to return the parent class's getter, but you need to invoke the getter, not return it.

这篇关于在 Python 中覆盖继承属性的 getter 和 setter的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆