网站制作学习网Python→正文:python 多重继承 super的运行顺序
字体:

python 多重继承 super的运行顺序

Python 2024/6/25 21:59:25  点击:不统计

www-fo-a-sp.cn
 python 在写代码时最好不要用多重继承,如果使用,不要使用__init__ 方法。

可以采用 属性方法的形式进行继承和运行,但具体是怎么运行的,看下面的例子:
class A:
def method(self):
print("A method")


class B(A):
def method(self):
super().method()
print("B method")


class C(A):
def method(self):
super().method()
print("C method")


class D(B, C):
def method(self):
super().method()
print("D method")


if __name__ == "__main__":
d = D()
d.method()
"""result
A method
C method
B method
D method
为什么C在 B 之前?

因为python的MRO(Method Resolution Order)是C3算法,C3算法是先从左到右,从上到下的顺序来决定类的继承顺序。
D 请求method ,遇到 super, super 有两个 先找到 B 再找到 C
B 请求method ,遇到 super, super().method() 会调用 C.method(),因为 C 在 B 的 MRO 之后。
super() 会按照 D 的 MRO 来查找下一个方法。D 的 MRO 是 [D, B, C, A, object],因此 super() 在 D 中会调用 B.method()。也就是说 super() 会顺序查找对应对象,调用对应方法
C 请求method ,遇到 super, super A 再找到 输出 A method
然后运行 C 的 method后面部分 输出 C method
然后运行 B 的 method后面部分 输出 B method
然后运行 D 的 method后面部分 输出 D method
"""

原文章%77w%77%2Ef%6F%72%61%73%70%2E%63n

·上一篇:python 浅拷贝 深拷贝 >>    ·下一篇:python 将类方法转换为静态属性方法 >>
推荐文章
最新文章