2

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... :/

Mizipzor
  • 51,151
  • 22
  • 97
  • 138
ADLR
  • 33
  • 4

3 Answers3

4

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__.

kennytm
  • 510,854
  • 105
  • 1,084
  • 1,005
4

You need to explicitly call the base class constructor like so:

class B(A):
    def __init__(self):
        super(B, self).__init__()

In python 3.0 the following is equivilent:

class B(A):
    def __init__(self):
        super().__init__()
Mizipzor
  • 51,151
  • 22
  • 97
  • 138
1

You didn't call the ancestor constructor, use the super() call for this

class B(A):
    def __init__(self):
        super(B, self).__init__()
        print "Class B"
Cédric Julien
  • 78,516
  • 15
  • 127
  • 132