Python属性和方法重写问题:为什么子类属性仍调用基类的方法 [英] Python property and method override issue: why subclass property still calls the base class's method

查看:70
本文介绍了Python属性和方法重写问题:为什么子类属性仍调用基类的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个例子

class A(object):
        def f1(self):
                return []
        test1 = property(f1)


class B(A):
        def f1(self):
                return [1, 2]

if __name__ == "__main__":
        b = B()
        print b.test1

我希望输出为[1,2],但是它将输出[].

I expect the output to be [1, 2], but it prints [] instead.

这与我的预期相反.

我在代码中犯了任何错误吗?如果没有,我想它是这样工作的,因为当创建属性test1时,它绑定到了基类A的f1函数.实现我想要的目标的可能替代实现方式是什么?

Did I make any mistake in the code? If not, I suppose it works this way because when the property test1 is created, it is bound to the f1 function of the base class A. What is a possible alternative implementation to achieve what I want?

推荐答案

如果您不想污染类名称空间,则可以使用lambda函数推迟对f1的查找.

You can defer the lookup of f1 with a lambda function if you don't wish to pollute the class namespace

class A(object):

        def f1(self):
                return []

        test1 = property(lambda x:x.f1())

这篇关于Python属性和方法重写问题:为什么子类属性仍调用基类的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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