Python super arguments | Example code

The super() doesn’t know what class it’s being called in. we have to tell it which class’s parent’s function want to get. It is called super argument in Python.

Python super arguments example

Simple example code in Python 3 this works:- create a Vehicle class and want to also have a Car a class derived from it that calls the parent constructor.

class Vehicle:
    def __init__(self):
        print('Vehicle __init__() called')


class Car(Vehicle):
    def __init__(self):
        super().__init__()


car = Car()

Output:

Python super arguments

Source: stackoverflow.com

Python multiple inheritance passing arguments to constructors using super

When dealing with multiple inheritances in general, your base classes should be designed for multiple inheritances.

class A(object):
    def __init__(self,a):
        self.a=a

class B(A):
    def __init__(self,b,**kw):
        self.b=b
        super(B,self).__init__(**kw)

 class C(A):
    def __init__(self,c,**kw):
        self.c=c
        super(C,self).__init__(**kw)

class D(B,C):
    def __init__(self,a,b,c,d):
        super(D,self).__init__(a=a,b=b,c=c)
        self.d=d

Do comment if you have any doubts and suggestions on this Python super topic.

Note: IDE: PyCharm 2021.1.3 (Community Edition)

Windows 10

Python 3.7

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.