本文介绍了为什么当我们声明子类的对象时不调用超类的构造函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是一个Java程序员,初学者在Python编程。我注意到了python编程中的意外行为。我期待打印序列作为 B类,A类构造函数。但它只是执行A的构造函数。

I am a Java programmer, beginner in Python programming. I have noticed unexpected behavior in python programming. I was expecting the print sequence as B class ,A Class constructors. But it's executing constructor of A only.

输出为它的构造函数,你能帮助我理解执行的流程。提前感谢

Output as "Its Constructor of A",Could you please help me to understand flow of execution. Thanks in advance

class B:
    def __init__(self):
        print 'Its constructor of B'    

class A(B):
    def __init__(self):
        print 'Its constructor of A'
        #B.__init__(self)

if __name__=='__main__':
    obj=A()


推荐答案

在python中,你应该调用父类的初始化器(这就是如何实际调用 __ init __ 方法 - constructor

In python you should call the parent's initializer (that's how the __init__ method is actually called, - "constructor" is something else) explicitly.

您可以像在注释行中所做的一样。更好的是,你应该使用 super 函数,计算出哪个父类为你访问。它只适用于尽管(基本上,这意味着,你的类层次结构的根必须继承自 object )。

You can do it like you did in the commented out line. Better yet, you should use the super function, that figures out, which parent to access for you. It only works with new-style classes though (basically, that means, that the root of your class hierarchy must inherit from object).

这篇关于为什么当我们声明子类的对象时不调用超类的构造函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-21 13:43