无法创建一致的方法解决方案..为什么?

时间:2015-12-03 08:08:52

标签: 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() 

我收到错误: - 无法创建一致的方法解析..为什么?

1 个答案:

答案 0 :(得分:3)

D继承A B 都有say_hello函数。 B继承自A

您不能乘以从基类后跟派生类的继承 定义满足通常的MRO约束/保证的一致MRO是不可能的。如上所述here

您现在调用super(D, self).say_hello()并且python不知道要选择哪个say_hello AB?!

这个例子可行:

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,例如甲