简体   繁体   English

在A - > B - > C继承链中不调用构造函数B.

[英]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类时,输出为:

Baz 巴兹

Foo

Why isn't Bar's constructor isn't called? 为什么没有调用Bar的构造函数?

The call to super() takes the current class as the first argument, not the super class ( super() works that out for itself). super()的调用将当前类作为第一个参数,而不是超类( super()为自己工作)。 In this case, the following should fix it... note the change to both super() calls: 在这种情况下,以下应该修复它...注意对两个super()调用的更改:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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