我试图通过使用可变方法名称来调用父类(super class)的方法。通常,我会认为以下两行代码是等效的:
someObj.method()
someObj.__getattribute__( 'method' )()
事实上我相信,这也是我使用第一行时实际发生的情况。然而,在下面的例子中,第二行产生了一个奇怪的问题。
我使用 super
构造一个超对象并调用父类(super class)的方法。直接按预期工作,但是使用 __getattribute__
首先获取方法,导致无限循环,一次又一次地调用子类的方法。
请看下面的代码:
class A:
def example ( self ):
print( 'example in A' )
class B ( A ):
def example ( self ):
print( super( B, self ).example )
print( super( B, self ).__getattribute__( 'example' ) )
super( B, self ).example()
#super( B, self ).__getattribute__( 'example' )()
print( 'example in B' )
x = B()
x.example()
如果您运行该代码,一切都会按预期运行,您应该会得到类似这样的输出:
<bound method B.example of <__main__.B object at 0x01CF6C90>>
<bound method B.example of <__main__.B object at 0x01CF6C90>>
example in A
example in B
所以这两种方法,一种是直接访问,另一种是通过 __getattribute__
,看起来是一样的。但是,如果您用注释掉的行替换方法调用,您最终会遇到递归运行时错误。
为什么会发生这种情况,更重要的是,当我使用工作线时,我如何才能以与 python 内部相同的方式实际访问该方法?
编辑
当我认为我已经尝试了所有方法时,我发现这是可行的:
super.__getattribute__( super( B, self ), 'example' )()
它实际上等于super( B, self ).example
。
最佳答案
不要为此使用__getattribute__
:它不会像您认为的那样工作。 (它是 Python 机制的一个专门部分,主要用于实现新的属性访问魔法。)
对于正常的属性访问,使用 getattr
/setattr
/delattr
内置函数:
self.example == getattr(self, 'example')
super(B, self).example == getattr(super(B, self), 'example')
(如果您想了解 __getattribute__
的作用,请阅读 Descriptor HowTo Guide 和 Python Data model 引用。)
关于python - 调用变量父类(super class)方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3847919/