【问题标题】:Does order of class bases in python matter? [duplicate]python中类基的顺序重要吗? [复制]
【发布时间】:2020-09-22 21:52:17
【问题描述】:

下面的两个类有(有意义的)区别吗?

class A(Foo, Bar):
    ...

class B(Bar, Foo):
    ...

【问题讨论】:

  • 简短回答:是的。谷歌“Python MRO”了解详情。 (但如果 FooBar 没有共同的方法名称,并且没有任何共同的基类,则不会。)

标签: python method-resolution-order


【解决方案1】:

python 中类基的顺序重要吗?

是的,确实如此。考虑以下几点:

class A:
    def foo(self):
        print('class A')
class B:
    def foo(self):
        print('class B')
class C(A, B):
    pass

c = C()
c.foo() # class A

方法是从左到右解析的——例如,在示例中,foo 方法来自类 A,因为 A 在 B 之前。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-03-30
    • 2015-07-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多