Peter Chao Peter Chao - 3 months ago 7
Python Question

Python class inheritance

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

Answer

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
Comments