简体   繁体   中英

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM