如果该属性在派生类中被覆盖,如何调用基类的属性? [英] How to call a property of the base class if this property is being overwritten in the derived class?

查看:21
本文介绍了如果该属性在派生类中被覆盖,如何调用基类的属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在将我的一些类从广泛使用 getter 和 setter 更改为更像 Python 一样使用属性.

I'm changing some classes of mine from an extensive use of getters and setters to a more pythonic use of properties.

但是现在我卡住了,因为我之前的一些getter或setter会调用基类的相应方法,然后执行其他操作.但是如何通过属性来实现呢?如何调用父类中的属性getter或setter?

But now I'm stuck because some of my previous getters or setters would call the corresponding method of the base class, and then perform something else. But how can this be accomplished with properties? How to call the property getter or setter in the parent class?

当然只是调用属性本身会产生无限递归.

Of course just calling the attribute itself gives infinite recursion.

class Foo(object):

    @property
    def bar(self):
        return 5

    @bar.setter
    def bar(self, a):
        print a

class FooBar(Foo):

    @property
    def bar(self):
        # return the same value
        # as in the base class
        return self.bar # --> recursion!

    @bar.setter
    def bar(self, c):
        # perform the same action
        # as in the base class
        self.bar = c    # --> recursion!
        # then do something else
        print 'something else'

fb = FooBar()
fb.bar = 7

推荐答案

你可能认为你可以调用由属性调用的基类函数:

You might think you could call the base class function which is called by property:

class FooBar(Foo):

    @property
    def bar(self):
        # return the same value
        # as in the base class
        return Foo.bar(self)

虽然这是我认为最明显的尝试 - 它不起作用,因为 bar 是一个属性,而不是可调用的.

Though this is the most obvious thing to try I think - it does not work because bar is a property, not a callable.

但是一个属性只是一个对象,通过getter方法找到对应的属性:

But a property is just an object, with a getter method to find the corresponding attribute:

class FooBar(Foo):

    @property
    def bar(self):
        # return the same value
        # as in the base class
        return Foo.bar.fget(self)

这篇关于如果该属性在派生类中被覆盖,如何调用基类的属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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