使用多重继承时如何调用第二个超级方法?

时间:2020-09-17 13:09:33

标签: python python-3.x

class Foo1:
    def hi(self, name):
        print('Oh hi there %s.' % name)

class Foo2:
    def hi(self, name):
        print('Hi %s, how ya doing?' % name)

class Bar(Foo1, Foo2):
    def hi(self, name):
       super(Bar, self).hi(name)

bar = Bar()
bar.hi('John')

输出:

Oh hi there John.

除了交换“ Foo1,Foo2”的顺序之外,如何从Bar访问Foo2的super方法?

1 个答案:

答案 0 :(得分:3)

如果您想绕过正常的方法解析顺序,那么您将陷入困境。要么

  1. 假装是您在MRO中真正想要的班级之前的班级:

    def hi(self, name):
        super(Foo1, self).hi(name)  # I'm really Bar's method, but lying to say I'm Foo1's
    
  2. 显式调用您关心的类(手动传递self):

    def hi(self, name):
        Foo2.hi(self, name)  # Looking it up directly on the class I want
    

注意:如果您使用的是Python 3,并且想要普通的MRO,则根本不需要将参数传递给super(),这将调用Foo1.hi就好了:

   def hi(self, name):
       super().hi(name)