2

I have this code:

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

class B(A):
    def __init__(self):
        print "B"
x=B()
print "Done"

the result is: "B" gets printed why does it not print "A", eventhough class B inheritance A

2
  • 2
    Because you're overriding the init method? Commented Aug 11, 2016 at 0:07
  • Python doesn't automatically call the superclass constructor for you; you need to explicitly call it yourself. The fact that this just passes silently is one of the design flaws of Python's class system implementation. Commented Aug 11, 2016 at 0:11

1 Answer 1

6

If you want to use A's __init__ while also using B's __init__, then try:

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

class B(A):
    def __init__(self):
        A.__init__(self)
        print "B"
x=B() 
print "Done"

Or, if you would prefer not to mention the superclass by name:

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

class B(A):
    def __init__(self):
        super(B, self).__init__()
        print "B"
x=B()
print "Done"

Both of these produce the output:

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

1 Comment

Never use super(self.__class__, self). It fails as soon as you make a descendant of B and self.__class__ isn't B any more.

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.