python 中子类为什么要显示的调用父类的构造函数
迷茫
迷茫 2017-04-17 13:16:46
0
2
801

解释器不自动调用么?

迷茫
迷茫

业精于勤,荒于嬉;行成于思,毁于随。

reply all(2)
Peter_Zhu

Because the subclass cannot infer how to call the constructor of the parent class, such as

class A():
  def __init__(a, b):
    pass

class B(A):
  def __init__(c):
    pass

Observe the processing of the C++ constructor, pay attention to item 5

  1. If the subclass does not define a constructor, the parameterless constructor of the parent class is called.
  2. If the subclass defines a constructor, whether parameterless or with parameters, when creating an object of the subclass, first execute the parent class's parameterless constructor, and then execute your own constructor.
  3. When creating a subclass object, if the constructor of the subclass does not explicitly call the constructor of the parent class, the default no-argument constructor of the parent class will be called.
  4. When creating a subclass object, if the constructor of the subclass does not explicitly call the constructor of the parent class and the parent class itself provides a parameterless constructor, the parent class's own parameterless constructor will be called.
  5. When creating a subclass object, if the constructor of the subclass does not explicitly call the constructor of the parent class and the parent class only defines its own constructor with parameters, an error will occur (if the parent class only has a constructor with parameters , the subclass must explicitly call this constructor with parameters).

The constructor of the subclass may not have the same number and order of parameters as the parent class, so it is impossible to guess how to call the constructor of the parent class.
For a language like Python that can only define one "constructor", there is no guarantee that it will have a parameterless constructor like C++, so... it can only be called manually

阿神

In order to pass parameters to the constructor of the parent class instead of calling the constructor of the parent class by default

(The way Python calls parent class functions is quite ugly

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template