Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inheritance in python and constructor calls

Tags:

python

The output is:

Class A
Class B
printout

Given code:

class A(object):
    def __init__(self):
        print "Class A"
    def printout(self):
        print "printout"

class B(A):
    def __init__(self):
        print "Class B"

def main():
    myA = A()
    myB = B()
    myB.printout()

if __name__ == '__main__':
    main()

I was hoping for:

Class A
Class A
Class B
printout

as result... :/

like image 404
ADLR Avatar asked Dec 10 '25 09:12

ADLR


1 Answers

It's because you did not call the superclass's __init__.

class B(A):
    def __init__(self):
        A.__init__(self)
#       ^^^^^^^^^^^^^^^^ this have to be explicitly added
        print "Class B"

In Python 3.x you could use super().__init__() instead of A.__init__(self), but you're still explicitly invoking the superclass's __init__.

like image 109
kennytm Avatar answered Dec 12 '25 21:12

kennytm



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!