V2EX = way to explore
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
saximi
V2EX  ›  Python

请教一个关于多重继承的问题

  •  
  •   saximi · 2017-09-24 23:21:40 +08:00 · 1981 次点击
    这是一个创建于 2404 天前的主题,其中的信息可能已经有所发展或是发生改变。
    class Init(object):
        def __init__(self,value):
            print("enter Init")
            self.val=value 
    class Add2(Init):
        def __init__(self,val):
            print("enter Add2")
            super(Add2,self).__init__(val)
            self.val+=2 
    class Mul5(Init):
        def __init__(self,val):
            print("enter Mul5")
            super(Mul5,self).__init__(val)
            self.val*=5 
    class Pro(Mul5,Add2): 
        pass
    class Incr(Pro):
        csup=super(Pro) 
        def __init__(self,val):
            self.csup.__init__(val)
            self.val+=1
            print("Incr.__init;val=",self.val)
     
    p=Incr(5) 
    print(p.val)
    
    
    上面程序输出如下: 
    enter Mul5
    enter Add2
    enter Init  
    36
    
    我认为在 Incr()生成实例时的语句执行顺序应该是:
    先执行 Incr 定义中的 super.__init__方法,因为父类 Pro 没有__init__方法,便会找到 Pro 的父类 Mul5 的__init__方法,进而通过 super()往上找到 Mul5 的父类 Init,执行完 Init.__init__方法后,Incr 的实例化就算结束了。
    但是从输出来看,实际上在执行完 Mul5 的__init__方法后,竟然去执行 Add2 的__init__方法,也就是把 Pro 的两个父类的__init__方法都执行了?
    
    难道说,在执行 Pro 的__init__方法时,会把 Pro 的所有父类都遍历一下,只要其父类有__init__方法的都会去执行,而不是在执行完 Pro 的第一个有__init__方法的父类的方法后就结束?
    恳请大家指点,感谢!
    
    
    3 条回复    2017-09-25 01:59:16 +08:00
    zeroten
        1
    zeroten  
       2017-09-25 00:21:54 +08:00   ❤️ 1
    MRO 的知识,这篇文章讲的挺好的 https://laike9m.com/blog/li-jie-python-super,70/
    flaneurse
        2
    flaneurse  
       2017-09-25 01:58:51 +08:00
    新式类的确是这样的
    flaneurse
        3
    flaneurse  
       2017-09-25 01:59:16 +08:00
    看一楼↗
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   3432 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 26ms · UTC 00:42 · PVG 08:42 · LAX 17:42 · JFK 20:42
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.