开发者

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜