代码之家  ›  专栏  ›  技术社区  ›  poke

调用变量超类方法

  •  1
  • poke  · 技术社区  · 15 年前

    我试图通过使用变量方法名来调用超类的方法。通常,我会将以下两行代码视为等效代码:

    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 .

    2 回复  |  直到 15 年前
        1
  •  5
  •   Pi Delport    15 年前

    使用 __getattribute__ 为此:它不做你认为它做的事。(它是Python机器的一个专门部分,主要用于实现新的属性访问魔法。)

    getattr / setattr delattr 内置:

    self.example           == getattr(self, 'example')
    super(B, self).example == getattr(super(B, self), 'example')
    

    (如果你想了解 __获取属性__ 是的,读一下 Descriptor HowTo Guide Data model 参考。)

        2
  •  0
  •   Ignacio Vazquez-Abrams    15 年前

    example a的属性 B 对象生成的绑定副本 B.example . 调用此函数将导致递归错误。你的电话 A.__getattribute__() B类