我试图通过使用变量方法名来调用超类的方法。通常,我会将以下两行代码视为等效代码:
someObj.method()
someObj.__getattribute__( 'method' )()
我用
super
__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
__获取属性__
,看起来一模一样。但是,如果用注释掉的行替换方法调用,则最终会出现递归运行时错误。
编辑
super.__getattribute__( super( B, self ), 'example' )()
实际上等于
super( B, self ).example
.