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()。但是导致parent2和c.bar()的c.foo()是错误的。请指出问题并提供解决方案。
答案 0 :(得分:4)
您可以直接在父类上调用方法,手动提供self
参数。这应该为您提供最高级别的控制,并且是最容易理解的方式。从其他角度来看,它可能不是最理想的。
这里只有Child
类,其余代码保持不变:
class Child(Parent1, Parent2):
def foo(self):
Parent1.foo(self)
def bar(self):
Parent2.bar(self)
使用所描述的更改运行代码段会产生所需的输出:
P1 foo
P2 bar