Accesing the parent __init__ variable to Child Python

Hello im trying to make a oop function but im currently stuck on how can i inherit the __init__ arguments of my parent class to the child class, is there a method that can i use to adapt the variable from my main to use in child?

class a:
    def __init__(self, name):
        self.name = name
        
class b(a):
    def __init__(self, age):
        super().__init__()
        self.age = age
        

When i trying to use the name from the parent it errors.

b('joe', 40)

> Traceback (most recent call last):
File "<string>", line 11, in <module>
TypeError: __init__() takes 2 positional arguments but 3 were given> 

>Solution :

In the b class, you need to include the name argument in the __init__ method and pass it to the super() method as shown below:

class a:
    def __init__(self, name):
        self.name = name
        
class b(a):
    def __init__(self, name, age):
        super().__init__(name)
        self.age = age

Now you can create an instance of the b class and pass the name and age arguments as follows:

b('joe', 40)

This will correctly initialize the name attribute inherited from the a class and the age attribute in the b class.

Leave a Reply