How to invoke the super constructor in Python?

后端 未结 7 2411
我寻月下人不归
我寻月下人不归 2020-11-22 10:48
class A:
    def __init__(self):
        print(\"world\")

class B(A):
    def __init__(self):
       print(\"hello\")

B()  # output: hello

In all

7条回答
  •  旧巷少年郎
    2020-11-22 11:38

    Short Answer

    super(DerivedClass, self).__init__()
    

    Long Answer

    What does super() do?

    It takes specified class name, finds its base classes (Python allows multiple inheritance) and looks for the method (__init__ in this case) in each of them from left to right. As soon as it finds method available, it will call it and end the search.

    How do I call init of all base classes?

    Above works if you have only one base class. But Python does allow multiple inheritance and you might want to make sure all base classes are initialized properly. To do that, you should have each base class call init:

    class Base1:
      def __init__():
        super(Base1, self).__init__()
    
    class Base2:
      def __init__():
        super(Base2, self).__init__()
    
    class Derived(Base1, Base2):
      def __init__():
        super(Derived, self).__init__()
    

    What if I forget to call init for super?

    The constructor (__new__) gets invoked in a chain (like in C++ and Java). Once the instance is created, only that instance's initialiser (__init__) is called, without any implicit chain to its superclass.

提交回复
热议问题