Why not constructor of super class invoked when we

2020-02-29 19:23发布

I am a Java programmer, beginner in Python programming. I have noticed unexpected behavior in python programming. I was expecting the print sequence as B class ,A Class constructors. But it's executing constructor of A only.

Output as "Its Constructor of A",Could you please help me to understand flow of execution. Thanks in advance

class B:
    def __init__(self):
        print 'Its constructor of B'    

class A(B):
    def __init__(self):
        print 'Its constructor of A'
        #B.__init__(self)

if __name__=='__main__':
    obj=A()

1条回答
Root(大扎)
2楼-- · 2020-02-29 20:18

In python you should call the parent's initializer (that's how the __init__ method is actually called, - "constructor" is something else) explicitly.

You can do it like you did in the commented out line. Better yet, you should use the super function, that figures out, which parent to access for you. It only works with new-style classes though (basically, that means, that the root of your class hierarchy must inherit from object).

查看更多
登录 后发表回答