无法创建一致的方法解析。为什么?
Cannot create a consistent method resolution.. Why?
我在多重继承中遇到错误。由于我是 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()
我收到错误:- 无法创建一致的方法解析。为什么?
D
继承A
和B
和两者都有一个函数say_hello
.并且 B
继承自 A
.
您不能从基础 class 后跟派生的 class
相乘继承
不可能定义一个一致的 MRO 来满足通常的 MRO constraints/guarantees。如上所述here
你现在打电话给 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
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()
继承树:
A
/
| B
| |
| C
\ /
D
Python 现在选择专业化程度最低的 say_hello,例如答.
我在多重继承中遇到错误。由于我是 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()
我收到错误:- 无法创建一致的方法解析。为什么?
D
继承A
和B
和两者都有一个函数say_hello
.并且 B
继承自 A
.
您不能从基础 class 后跟派生的 class
相乘继承
不可能定义一个一致的 MRO 来满足通常的 MRO constraints/guarantees。如上所述here
你现在打电话给 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
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()
继承树:
A
/
| B
| |
| C
\ /
D
Python 现在选择专业化程度最低的 say_hello,例如答.