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

标签 python oop inheritance constructor

我有以下继承链:

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

当实例化 Baz 类时,输出是:

Baz

Foo

为什么不调用 Bar 的构造函数?

最佳答案

super() 的调用将当前类作为第一个参数,而不是父类(super class)(super() 自行解决)。在这种情况下,以下应该修复它...注意对两个 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__()

关于python - 构造函数 B 未在 A -> B -> C 继承链中调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5318849/

相关文章:

html - HTML 标签可以继承父/封闭标签的类吗?

c++ - 如何用非虚函数覆盖虚函数?

python - 使 django 应用程序在 127.0.0.1 :8000 accessible everywhere? 上运行

python - 如何在Python中实现动态路由?

python - 抓取外文网页标题后在终端获取解码结果

php - 什么时候从程序切换到 OOP?

java - Hibernate - IllegalArgumentException 在调用模型的 getter 时发生

python multiprocessing - 进程挂起加入大队列

c++ - 在cpp中将对象写入文件

java - 在 Java 运行时选择要扩展的子类