Mah*_*arg 1 python multiple-inheritance
我在多重继承中遇到错误。由于我是Python新手,所以我不明白为什么我不能这样做。
class A(object):
def say_hello(self):
print 'A says hello'
class B(A):
def say_hello(self):
super(B, self).say_hello()
print 'B says hello'
class C(A):
def say_hello(self):
super(C, self).say_hello()
print 'C says hello'
class D(A, B):
def say_hello(self):
super(D, self).say_hello()
print 'D says hello'
DD = D()
DD.say_hello()
Run Code Online (Sandbox Code Playgroud)
我收到错误:- 无法创建一致的方法分辨率。为什么?
D继承A 和 B,两者都有一个功能say_hello。并B继承自A.
您不能从基类乘以继承,然后再继承派生类。
不可能定义一个一致的 MRO 来满足通常的 MRO 约束/保证。如此处所述
你现在打电话super(D, self).say_hello(),python 不知道该say_hello选择哪个。
A或者B?!
这作为例子可以工作:
class D(A): #D only inherits A not A and B
def say_hello(self):
super(D, self).say_hello()
print 'D says hello'
DD = D()
DD.say_hello()
#output
>>>A says hello
>>>D says hello
#There are 2 connections to As say_hello
A-----
/ \ |
B C |
| /
\ /
D
Run Code Online (Sandbox Code Playgroud)
PS:请使用“self”作为第一个参数的名称
更新:As如果继承看起来像这样,
它会选择say_hello
class A(object):
def say_hello(cls):
print 'A says hello'
class B():
def say_hello(cls):
print 'B says hello'
class C(B):
def say_hello(cls):
super(C, cls).say_hello()
print 'C says hello'
class D(A, C):
def say_hello(self):
super(D, self).say_hello()
print 'D says hello'
DD = D()
DD.say_hello()
Run Code Online (Sandbox Code Playgroud)
继承树:
A
/
| B
| |
| C
\ /
D
Run Code Online (Sandbox Code Playgroud)
Python 现在选择专业化程度最低的 say_hello,例如 A。