class P(object): def __init__(self, a, b): self.a = a self.b = b class C(P): def __init__(self, c): P.__init__() self.c = c obj = C(a, b, c) #want to instantiate a C with something like this
I want to define C
class object without rewriting all the P
class constructor argument in C
's constructor, but the above code doesn't seem to work. What is the right approach to do this?
Clarification:
The idea is to avoid putting parent class's constructor arguments in child class's constructor. It's just repeating too much. All my parent and child classes have many arguments to take in for constructors, so repeating them again and again is not very productive and difficult to maintain. I'm trying to see if I can only define what's unique for the child class in its constructor, but still initialize inherited attributes.
To explicitly call the superclass constructor from the subclass constructor, we use super() . It's a special form of the super keyword. super() can be used only inside the subclass constructor and must be the first statement.
If we call "super()" without any superclass Actually, nothing will be displayed. Since the class named Object is the superclass of all classes in Java. If you call "super()" without any superclass, Internally, the default constructor of the Object class will be invoked (which displays nothing).
The constructors of the subclass can initialize only the instance variables of the subclass. Thus, when a subclass object is instantiated the subclass object must also automatically execute one of the constructors of the superclass. To call a superclass constructor the super keyword is used.
Constructors are not inherited. The superclass constructor can be called from the first line of a subclass constructor by using the keyword super and passing appropriate parameters to set the private instance variables of the superclass.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With