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.
You can call parent class constructor by passing self and required arguments
In Python2, you write
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 writeDemo:
Response to your comment:
You could achieve that effect with the *args or **kwargs syntax, for example:
or