Passing arguments to superclass constructor without repeating them in childclass constructor

In Python2, you write

class C(P):
    def __init__(self, a, b, c):
        super(C, self).__init__(a, b)
        self.c = c

where the first argument to super is the child class and the second argument is the instance of the object which you want to have a reference to as an instance of its parent class.

In Python 3, super has superpowers and you can write

class C(P):
    def __init__(self, a, b, c):
        super().__init__(a, b)
        self.c = c

Demo:

obj = C(1, 2, 3) 
print(obj.a, obj.b, obj.c) # 1 2 3

Response to your comment:

You could achieve that effect with the *args or **kwargs syntax, for example:

class C(P):
    def __init__(self, c, *args):
        super(C, self).__init__(*args)
        self.c = c

obj = C(3, 1, 2)
print(obj.a, obj.b, obj.c) # 1 2 3

or

class C(P):
    def __init__(self, c, **kwargs):
        super(C, self).__init__(**kwargs)
        self.c = c

obj = C(3, a=1, b=2)
print(obj.a, obj.b, obj.c) # 1 2 3

obj = C(a=1, b=2, c=3)
print(obj.a, obj.b, obj.c) # 1 2 3

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)