Python Forum
Is it mandatory to call superclass init inside the class init?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Is it mandatory to call superclass init inside the class init?
#4
It's not mandatory. But if you want the A.__init__ method to handle its own initialization and B.__init__() just something bit more, you wave to call it.

And the proper way is to call super():

class B(A):
    def __init__(self):
        super.__init__() # instead of A.__init(self)
When you use multiple inheritances don't calling super() could cause some issues.

In [1]: class A:
   ...:     def __init__(self):
   ...:         print('A')
   ...:

In [2]: class B(A):
   ...:     def __init__(self):
   ...:         A.__init__(self)
   ...:         print('B')
   ...:

In [3]: class C(A):
   ...:     def __init__(self):
   ...:         A.__init__(self)
   ...:         print('C')
   ...:

In [4]: class D(B, C):
   ...:     def __init__(self):
   ...:         B.__init__(self)
   ...:         C.__init__(self)
   ...:         print('D')
   ...:

In [5]: obj = D()
A
B
A
C
As you can see A is called twise.
"As they say in Mexico 'dosvidaniya'. That makes two vidaniyas."
https://freedns.afraid.org
Reply


Messages In This Thread
RE: Is it mandatory to call superclass init inside the class init? - by wavic - Feb-14-2020, 09:16 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  How do I call sys.argv list inside a function, from the CLI? billykid999 3 811 May-02-2023, 08:40 AM
Last Post: Gribouillis
  How to call a class in other class? 3lnyn0 3 947 Oct-24-2022, 09:18 AM
Last Post: GenTorossi
  PyRun_SimpleFile calling multiprocessing Python Class cause endless init loop Xeno 2 1,064 Sep-19-2022, 02:32 AM
Last Post: Xeno
  Init an indefinite number of class MathisDELAGE 9 2,382 Feb-18-2022, 07:49 PM
Last Post: deanhystad
  Basic Inheritance, Why Use init udinjelek 5 2,202 Sep-29-2021, 06:03 PM
Last Post: deanhystad
  Practice problem using lambda inside the class jagasrik 3 2,197 Sep-12-2020, 03:18 PM
Last Post: deanhystad
  superclass and super() grkiran2011 1 1,755 Jun-20-2020, 04:37 AM
Last Post: deanhystad
  Error: How to to close and restart your shell after running 'conda init' angelica 3 10,293 May-27-2020, 10:00 AM
Last Post: snippsat
  How to read file inside class Mekala 11 12,604 May-02-2020, 11:36 AM
Last Post: snippsat
  Call a .xlsx file outside a class criscferr 2 1,886 Apr-24-2020, 04:23 PM
Last Post: criscferr

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020