• 技术文章 >Python技术 >Python基础教程

    如何实现python中super()多重继承?

    宋雪维宋雪维2020-12-07 16:45:24原创2756

    在计算机编程中,继承通过增强一致性来减少模块间的接口和界面,大大增加了程序的易维护性。之前小编向大家介绍了python中继承函数super()(https://www.py.cn/jishu/jichu/21695.html),不过当涉及到多继承情况时,一些调用方式就会产生差异,就需要做出相应的调整。那么,我们一起来看看多继承情况下,super()如何调用吧。

    实例:涉及多重继承

    代码:

    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    12

    13

    14

    15

    16

    17

    18

    19

    20

    21

    22

    23

    24

    25

    26

    27

    class Base(object):

        def __init__(self):

            print("enter Base")

            print("leave Base")

     

     

    class A(Base):

        def __init__(self):

            print("enter A")

            super(A,self).__init__()

            print("leave A")

     

     

    class B(Base):

        def __init__(self):

            print("enter B")

            super(B,self).__init__()

            print("leave B")

     

    class C(A,B):

        def __init__(self):

            print("enter C")

            super(C,self).__init__()

            print("leave C")

     

     

    c=C()

    输出

    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    C:\python36\python.exe E:/demo/testPyQt.py

    enter C

    enter A

    enter B

    enter Base

    leave Base

    leave B

    leave A

    leave C

     

    Process finished with exit code 0

    python中的super()方法设计目的是用来解决多重继承时父类的查找问题,所以在单重继承中用不用 super 都没关系,但是,在子类中需要调用父类时,使用super() 是一个好方法哦~

    专题推荐:pythonsuper多重继承
    上一篇:python列表如何使用sorted排序? 下一篇:format在python中参数能输出几次?

    相关文章推荐

    • python中如何分解质因数?

    全部评论我要评论

    © 2021 Python学习网 苏ICP备2021003149号-1

  • 取消发布评论
  • 

    Python学习网