search

Home  >  Q&A  >  body text

python 中子类为什么要显示的调用父类的构造函数

解释器不自动调用么?

迷茫迷茫2873 days ago862

reply all(2)I'll reply

  • 天蓬老师

    天蓬老师2017-04-17 13:18:46

    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

    reply
    0
  • 阿神

    阿神2017-04-17 13:18:46

    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

    reply
    0
  • Cancelreply