pok*_*oke 1 python super superclass
我试图通过使用变量方法名称来调用超类的方法.通常,我会看到以下两行代码是等效的:
someObj.method()
someObj.__getattribute__( 'method' )()
Run Code Online (Sandbox Code Playgroud)
事实上,我相信,这也是我使用第一行时实际发生的事情.但是,在下面的示例中,第二行产生了一个奇怪的问题.
我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()
Run Code Online (Sandbox Code Playgroud)
如果你运行该代码,一切都按预期工作,你应该得到类似于这样的输出:
<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
Run Code Online (Sandbox Code Playgroud)
因此,两种方法,即直接访问和一种通道__getattribute__,看起来都是相同的.但是,如果您通过注释掉的行替换方法调用,则最终会出现递归运行时错误.
为什么会发生这种情况,更重要的是,当我使用工作线时,如何以与python内部相同的方式实际访问该方法?
当我以为我已经尝试了所有东西时,我发现这是有效的:
super.__getattribute__( super( B, self ), 'example' )()
Run Code Online (Sandbox Code Playgroud)
它实际上等于super( B, self ).example.
不要使用__getattribute__此:它不会做什么,你认为它.(它是Python机器的一个专门部分,主要用于实现新的属性访问魔法.)
对于普通的属性访问,请使用getattr/ setattr/ delattrbuiltins:
self.example == getattr(self, 'example')
super(B, self).example == getattr(super(B, self), 'example')
Run Code Online (Sandbox Code Playgroud)
(如果您想了解__getattribute__它的作用,请阅读Descriptor HowTo指南和Python 数据模型参考.)