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

1
  • 1
    dont put pre tags around code segments, it removes the syntax highlight. Commented May 31, 2011 at 13:25

3 Answers 3

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

Sign up to request clarification or add additional context in comments.

Comments

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__()

Comments

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"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.