umbe1987 umbe1987 - 1 month ago 10
Python Question

passing class arguments defined in parent class from child class inheriting the parent

I am pretty new to OOP in python (ver. 3.5). I created a generic class and I would like to create a new one inheriting from it.

My parent class (say

A
) has two args defined within its
__init__()
method. How can I inherit those in my child class (say
B
) so that when I instantiate
B
I can pass it the args I would pass to
A
? I am actually trying to use the
super()
function, but I am not quite sure about the result.

I tried the below, but it gives me
TypeError: __init__() takes 1 positional argument but 3 were given


class A(): # parent class
def __init__(self, x, y):
self.x = x
self.y = y

class B(A): # child class
def __init__(self):
super().__init__(x, y)


And then I would do (e.g.)
b = B(5, 5)


EDIT 1

As my question was identified as duplicate of this answer, I would lke to state why it is different and why that answer did not help me to solve my problem:

I am not asking about how to access the parameters of a parent class from a child class, but if it was possible to instantiate a class with a parent class inherited, passing to it the arguments like if it was a call to the parent's class.

The answer is "I can't", unless I define again the same arguments in the child class
__init__()
method. Finally, as I said I am new to OOP, the indicated answer was not helpful, as the initial question was too difficult to understand to me (and it's not even in python).

Answer
class A(): # parent class
     def __init__(self, x, y):
         self.x = x
         self.y = y

class B(A): # child class
    def __init__(self, x, y):
        A.__init__(self, x, y)

So now you can use b = B(5, 5)

Comments