Sam*_*des 5 python oop multiple-inheritance python-2.7
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()
Run Code Online (Sandbox Code Playgroud)
目的是从 Parent1 继承 foo(),从 Parent2 继承 bar()。但是 c.foo() 对parent2 和 c.bar() 结果是错误的。请指出问题并提供解决方案。
您可以直接在父类上调用方法,self
手动提供参数。这应该为您提供最高级别的控制并且是最容易理解的方法。但从其他角度来看,这可能不是最理想的。
这只是Child
类,其余代码保持不变:
class Child(Parent1, Parent2):
def foo(self):
Parent1.foo(self)
def bar(self):
Parent2.bar(self)
Run Code Online (Sandbox Code Playgroud)
使用所描述的更改运行代码片段会产生所需的输出:
P1 foo
P2 bar
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
2050 次 |
最近记录: |