Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Constructor B is not called in an A -> B -> C inheritance chain

I have the following inheritance chain:

class Foo(object):
    def __init__(self):
        print 'Foo'

class Bar(Foo):
    def __init__(self):
        print 'Bar'
        super(Foo, self).__init__()

class Baz(Bar):
    def __init__(self):
        print 'Baz'
        super(Bar, self).__init__()

When instantiating Baz class the output is:

Baz

Foo

Why isn't Bar's constructor isn't called?

like image 597
the_drow Avatar asked Jan 28 '26 17:01

the_drow


1 Answers

The call to super() takes the current class as the first argument, not the super class (super() works that out for itself). In this case, the following should fix it... note the change to both super() calls:

class Foo(object):
    def __init__(self):
        print 'Foo'

class Bar(Foo):
    def __init__(self):
        print 'Bar'
        super(Bar, self).__init__()

class Baz(Bar):
    def __init__(self):
        print 'Baz'
        super(Baz, self).__init__()
like image 125
Jarret Hardie Avatar answered Jan 31 '26 06:01

Jarret Hardie