PyQt4: why do we need to pass the class name when calling super ()

as in the following code super(MdiChild, self).__init__(), we pass mdichild in superfunction. Please explain to me why and why it is used .__init__().

class MdiChild(QtGui.QTextEdit):
   sequenceNumber = 1

   def __init__(self):
      super(MdiChild, self).__init__()
+4
source share
2 answers

In python3.3 + you don't need to explicitly pass the class name, you can just do:

super().__init__()

Now notice what the superconstructor does not call . It simply provides an object in which you can access the attributes of this instance, as if it were an instance of the parent class. For example, you can call setText:

super().setText('Hello')  # calls QLineEdit.setText

python < 3.3 super . . , , , , , , , . , :

super(QLineEdit, self).__init__()

QLineEdit __init__() (.. grand-parent __init__()).

python3.3 "", super super(CurrentClass, self). .


, super:

In [1]: class MyBase(object):
   ...:     def __init__(self):
   ...:         print('MyBase.__init__() called')

In [2]: class MyChild(MyBase):
   ...:     def __init__(self):
   ...:         print('MyChild.__init__() called')
   ...:         super().__init__() # MyBase.__init__
   ...:         

In [3]: class MyGrandChild(MyChild):
   ...:     def __init__(self):
   ...:         print('MyGrandChild.__init__() called')
   ...:         super().__init__()  # MyChild.__init__
   ...:         print('Between super calls')
   ...:         super(MyChild, self).__init__()  # MyBase.__init__
   ...:         super(MyBase, self).__init__() # object.__init__ (does nothing)

In [4]: MyGrandChild()
MyGrandChild.__init__() called
MyChild.__init__() called
MyBase.__init__() called
Between super calls
MyBase.__init__() called

python < 3.3, , super() :

super(NameOfCurrentClass, self)

:

In [7]: class MyBase(object):
   ...:     def __init__(self):
   ...:         print('MyBase.__init__() called')

In [8]: class MyChild(MyBase):
   ...:     def __init__(self):
   ...:         print('MyChild.__init__() called')
   ...:         super(MyChild, self).__init__()

In [9]: class MyGrandChild(MyChild):
   ...:     def __init__(self):
   ...:         print('MyGrandChild.__init__() called')
   ...:         super(MyGrandChild, self).__init__()
   ...:         print('Between super calls')
   ...:         super(MyChild, self).__init__()
   ...:         super(MyBase, self).__init__()

In [10]: MyGrandChild()
MyGrandChild.__init__() called
MyChild.__init__() called
MyBase.__init__() called
Between super calls
MyBase.__init__() called

super(A, instance) : instance, A parent. "" MRO:

In [12]: MyGrandChild.__mro__
Out[12]: (__main__.MyGrandChild, __main__.MyChild, __main__.MyBase, builtins.object)

object, , , A, .

+2

C B B A foo C.

foo.__init__() - C.__init__(), B.__init__. , C, B.__init__ , B parent __init__ (.. A.__init__), (.. B.__init__)), B .

, , , .

0

Source: https://habr.com/ru/post/1534120/


All Articles