Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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> 

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading