Super init vs. parent.__init__

后端 未结 2 972
不思量自难忘°
不思量自难忘° 2021-01-31 16:37

A Python subclass can be initialized with or without a call to super(), as shown below

class Parent(object):
    ...

class Child(Parent):

    def          


        
2条回答
  •  庸人自扰
    2021-01-31 16:45

    The primary purpose of super(Child, self).__init__(self) is allow initialization run properly in the case of multiple inheritance with diamond inheritance structures. If you explicitly call the base class constructors with multiple inheritance some initializers may be called twice. With single inheritance, there is no functional difference between using super and explicitly invoking the base class __init__() method. Note that because all python new-style classes subclass object, multiple inheritance always involves diamond inheritance.

    super has a lesser benefit of reducing requires changes if you rename or change the base class.

    In python 3, the arguments to super are optional, so you can just do super().__init__(self). Python 2 still requires you to provide the arguments explicitly.

提交回复
热议问题