【问题标题】:Cannot create a consistent method resolution.. Why? [closed]无法创建一致的方法解决方案。为什么? [关闭]
【发布时间】:2016-03-07 18:09:11
【问题描述】:

我在多重继承中遇到错误。由于我是 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() 

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

【问题讨论】:

标签: python multiple-inheritance


【解决方案1】:

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”作为第一个参数的名称

更新: 如果继承看起来像这样,它将选择Assay_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,例如A.

【讨论】:

  • 它不会选择 A,因为它是该方法的较早基础吗?
  • @JLPeyret 对不起,我不明白你的问题。他当然会打电话给say_hello
  • 但是您没有回答他的问题,您只是删除了多重继承。我的问题是关于你的“蟒蛇不知道”这句话。我认为它会根据 OPs 的问题选择 A,但我怀疑 B 调用 A 本身可能会混淆它。
  • 我也这么认为.. JL Peyret
  • 您阅读了我提供的链接吗?关于如何构建继承树以及何时失败,有一个非常详细的解释。
猜你喜欢
  • 2011-12-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-02-07
  • 1970-01-01
相关资源
最近更新 更多