python 中的多重继承与 super

multiple inheritance in python with super

class Parent1(object):
    def foo(self):
        print "P1 foo"

    def bar(self):
        print "P1 bar"


class Parent2(object):
    def foo(self):
        print "P2 foo"

    def bar(self):
        print "P2 bar"



class Child(Parent1, Parent2):
    def foo(self):
        super(Parent1, self).foo()

    def bar(self):
        super(Parent2, self).bar()

c = Child() 
c.foo()
c.bar()

目的是继承Parent1的foo()和Parent2的bar()。但是 c.foo() 导致 parent2 和 c.bar() 导致错误。请指出问题并提供解决方案。

您可以直接在父 classes 上调用方法,手动提供 self 参数。这应该为您提供最高级别的控制,并且是最容易理解的方式。从其他角度来看,它可能不是最理想的。

这里只有 Child class,其余代码保持不变:

class Child(Parent1, Parent2):
    def foo(self):
        Parent1.foo(self)

    def bar(self):
        Parent2.bar(self)

运行 具有所述更改的代码段会产生所需的输出:

P1 foo
P2 bar

See this code running on ideone.com