Python 多重继承的问题 为什么以下代码里 Base 的 __init__ 没有被调用 - V2EX
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
doraemon1293

Python 多重继承的问题 为什么以下代码里 Base 的 __init__ 没有被调用

  •  
  •   doraemon1293 Jul 17, 2020 2771 views
    This topic created in 2129 days ago, the information mentioned may be changed or developed.
    class Base(): def __init__(self): print("Base") class First(Base): def __init__(self): super().__init__() print("first") class Second(Base): def __init__(self): print("second") class Third(First,Second): def __init__(self): super().__init__() print("third") Third() 

    为何输出结果为

    second

    first

    third

    为什么 First 中 super().init() 没有被调用呢

    如果代码改为

    class Base(): def __init__(self): print("Base") class First(Base): def __init__(self): super().__init__() print("first") class Second(Base): def __init__(self): super().__init__() print("second") class Third(First,Second): def __init__(self): super().__init__() print("third") Third() 

    则输出结果为

    Base

    second

    first

    third

    10 replies    2020-07-18 10:47:41 +08:00
    gwy15
        1
    gwy15  
       Jul 17, 2020
    调用 super() 的时候实际上会跟随 MRO 进行链式调用,在这个例子里面,调用链是(从左到右宽度优先搜索)
    `Third` -> `First` -> `Second` -> `Base` -> `object`
    可以用 `Third.mro()` 查看。

    因此,在调用的时候,Third.__init__ 里面 super().__init__() 实际调用的是 Second.__init__(self),而 Second.__init__ 里面没有继续调用 super,所以 Base 的 __init__ 没有调用。
    gwy15
        2
    gwy15  
       Jul 17, 2020
    上面有点笔误
    Third -> First -> Second -/-> Base
    >>> second
    >>> first
    >>> third
    marquina
        3
    marquina  
       Jul 17, 2020
    @gwy15 更准确地说,Third.__init__里的 super().__init__()调用的是 First.__init__,First.__init__里的 super().__init__调用的是 Second.__init__。
    marquina
        4
    marquina  
       Jul 17, 2020
    @gwy15 才看到你#2 的回复
    doraemon1293
        5
    doraemon1293  
    OP
       Jul 17, 2020
    感谢回答
    两种情况 打印 Third.__mro__ 结果都是
    (<class '__main__.Third'>, <class '__main__.First'>, <class '__main__.Second'>, <class '__main__.Base'>, <class 'object'>)
    多重继承 super 不是从左到右查找吗 为什么会调用 Second.__init__(self)

    我把打印的代码改成标注开始和结束
    ```
    class Base():
    def __init__(self):
    print("Base")

    class First(Base):
    def __init__(self):
    print("first start")
    super().__init__()
    print("first end")
    class Second(Base):
    def __init__(self):
    print("second start")
    # super().__init__()
    print("second end")

    class Third(First,Second):
    def __init__(self):
    super().__init__()
    print("third")
    print(Third.__mro__)
    Third()
    ```
    结果如下
    first start
    second start
    second end
    first end
    third
    为什么 first 先被调用 然而 first 里的 super().__init__()没有任何效果呢?
    doraemon1293
        6
    doraemon1293  
    OP
       Jul 17, 2020
    刚看到你的更正 请忽略我上面的回复
    为什么 First.__init__里的 super().__init__调用的是 Second.__init__。
    First 的 super 不应该调用他的父类 Base 吗?
    gwy15
        7
    gwy15  
       Jul 17, 2020
    @doraemon1293 super 是根据 MRO 链走的,不是“父类”。
    doraemon1293
        8
    doraemon1293  
    OP
       Jul 17, 2020
    @gwy15
    明白了 一直以为 super 是调用父类 多谢解答
    oahebky
        9
    oahebky  
       Jul 17, 2020 via Android
    这是个新式类+钻石继承的问题。

    没有什么特别的东西,就是“规定”。

    具体参见 《 learning Python 》(有中文版)类的高级主题部分 - 第 31 章。

    自认为没有能力解释得比书上更好,所以不多做解释,仅指路。
    HFcbyqP0iVO5KM05
        10
    HFcbyqP0iVO5KM05  
       Jul 18, 2020 via Android   1
    不如亲自看看 Python 之父当时解决 MRO 的思路:
    http://python-history.blogspot.com/2010/06/method-resolution-order.html?m=1
    About     Help     Advertise     Blog     API     FAQ     Solana     2982 Online   Highest 6679       Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 37ms UTC 02:44 PVG 10:44 LAX 19:44 JFK 22:44
    Do have faith in what you're doing.
    ubao msn snddm index pchome yahoo rakuten mypaper meadowduck bidyahoo youbao zxmzxm asda bnvcg cvbfg dfscv mmhjk xxddc yybgb zznbn ccubao uaitu acv GXCV ET GDG YH FG BCVB FJFH CBRE CBC GDG ET54 WRWR RWER WREW WRWER RWER SDG EW SF DSFSF fbbs ubao fhd dfg ewr dg df ewwr ewwr et ruyut utut dfg fgd gdfgt etg dfgt dfgd ert4 gd fgg wr 235 wer3 we vsdf sdf gdf ert xcv sdf rwer hfd dfg cvb rwf afb dfh jgh bmn lgh rty gfds cxv xcv xcs vdas fdf fgd cv sdf tert sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf shasha9178 shasha9178 shasha9178 shasha9178 shasha9178 liflif2 liflif2 liflif2 liflif2 liflif2 liblib3 liblib3 liblib3 liblib3 liblib3 zhazha444 zhazha444 zhazha444 zhazha444 zhazha444 dende5 dende denden denden2 denden21 fenfen9 fenf619 fen619 fenfe9 fe619 sdf sdf sdf sdf sdf zhazh90 zhazh0 zhaa50 zha90 zh590 zho zhoz zhozh zhozho zhozho2 lislis lls95 lili95 lils5 liss9 sdf0ty987 sdft876 sdft9876 sdf09876 sd0t9876 sdf0ty98 sdf0976 sdf0ty986 sdf0ty96 sdf0t76 sdf0876 df0ty98 sf0t876 sd0ty76 sdy76 sdf76 sdf0t76 sdf0ty9 sdf0ty98 sdf0ty987 sdf0ty98 sdf6676 sdf876 sd876 sd876 sdf6 sdf6 sdf9876 sdf0t sdf06 sdf0ty9776 sdf0ty9776 sdf0ty76 sdf8876 sdf0t sd6 sdf06 s688876 sd688 sdf86