V2EX = way to explore
V2EX 是一个关于分享和探索的地方
Sign Up Now
For Existing Member  Sign In
推荐学习书目
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 · Sep 24, 2017 · 2546 views
    This topic created in 3150 days ago, the information mentioned may be changed or developed.
    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 replies    2017-09-25 01:59:16 +08:00
    zeroten
        1
    zeroten  
       Sep 25, 2017   ❤️ 1
    MRO 的知识,这篇文章讲的挺好的 https://laike9m.com/blog/li-jie-python-super,70/
    flaneurse
        2
    flaneurse  
       Sep 25, 2017
    新式类的确是这样的
    flaneurse
        3
    flaneurse  
       Sep 25, 2017
    看一楼↗
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   4228 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 45ms · UTC 05:09 · PVG 13:09 · LAX 22:09 · JFK 01:09
    ♥ Do have faith in what you're doing.