开发者

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

开发者 https://www.devze.com 2023-02-16 21:14 出处:网络
I have the following inheritance chain: class Foo(object): def __init__(self): print \'Foo\' class Bar(Foo):

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

精彩评论

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

关注公众号