[英]Python property and method override issue: why subclass property still calls the base class's method
Here is an example 这是一个例子
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
I expect the output to be [1, 2], but it prints [] instead. 我希望输出为[1,2],但它会打印[]。
It is contrary to my expectation. 这与我的期望相反。
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?
如果没有,我认为它是这样工作的,因为当创建属性test1时,它被绑定到基类A的f1函数。有什么可能的替代实现来实现我想要的?
You can defer the lookup of f1
with a lambda function if you don't wish to pollute the class namespace 如果您不希望污染类命名空间,可以使用lambda函数推迟
f1
的查找
class A(object):
def f1(self):
return []
test1 = property(lambda x:x.f1())
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.
我认为它的工作原理是这样的,因为当创建属性test1时,它被绑定到基类A的f1函数。
Exactly correct. 完全正确。
What is a possible alternative implementation to achieve what I want?
什么是可能的替代实现来实现我想要的?
One more level of indirection: 另一个层次的间接:
class A(object):
def f1(self): return []
def _f1(self): return self.f1()
test1 = property(_f1)
class B(A):
def f1(self): return [1, 2]
A couple of alternatives I can think of: either repeat the call to property
in the subclass, 我能想到的几个替代方案:要么重复对子类中
property
的调用,
class B(A):
def f1(self):
return [1,2]
test1 = property(f1)
or base the property on another method which calls f1
: 或者将该属性基于另一个调用
f1
方法:
class A(object):
def f1(self):
return []
def _f1(self):
return self.f1()
test1 = property(_f1)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.