【问题标题】:Python Multiple inheritance doesn't seem to be "depth first". Or am i missing something obviousPython 多重继承似乎不是“深度优先”。还是我错过了一些明显的东西
【发布时间】:2022-11-01 12:44:20
【问题描述】:
class B:
    def f(self):
        return "p"

class C1(B):
   #no definition of f
   pass

class C2(B):
    def f(self):
        return "c2"

class G(C1,C2):
    pass


g = G()
print("I would expect this value to be 'p'. But it prints 'c2'",g.f())

根据python文档:https://docs.python.org/3/tutorial/classes.html#multiple-inheritance

对于大多数目的,在最简单的情况下,您可以将搜索从父类继承的属性视为深度优先、从左到右,而不是在层次结构中有重叠的同一类中搜索两次。因此,如果在 DerivedClassName 中找不到某个属性,则在 Base1 中搜索它,然后(递归地)在 Base1 的基类中,如果在那里没有找到,则在 Base2 中搜索,依此类推。

这绝对不会发生。

【问题讨论】:

  • 我怀疑这个例子算作“最简单的情况”。
  • 如果确定是发生这种情况,您只是误解了文档 - 请参阅下面的答案以获取可能有助于解释它的示例。

标签: python oop multiple-inheritance


【解决方案1】:

“这绝对不会发生。”是的。

考虑一下:

class A:
    def f(self):
        return "a"


class B:
    def f(self):
        return "b"


class C1(B):
    # no definition of f
    pass


class C2(B):
    def f(self):
        return "c2"


class G(C1, C2):
    pass


class H(C1, A):
    pass


g = G()
print("This prints 'c2' because it finds `f` in `C2` overriding the one in `B`.", g.f())
h = H()
print("This prints 'b' because it finds `f` in `B` ignoring the one in `A` even though it's 'closer'.", h.f())

【讨论】:

    猜你喜欢
    • 2019-09-18
    • 1970-01-01
    • 2015-06-21
    • 1970-01-01
    • 2014-03-02
    • 1970-01-01
    • 1970-01-01
    • 2021-10-12
    • 2018-01-09
    相关资源
    最近更新 更多