Accesing the parent __init__ variable to Child Python

Question:

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> 
Asked By: se6

||

Answers:

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.

Answered By: kenjoe41

The arguments from the child constructor need to be passed to the parent. This is because the child constructor overrides the method (i.e. replaces the constructor method) from the parent. Calling super allows you to access the original parent constructor, which will need to be provided the appropriate arguments.

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

As you might notice, this means you need to write a lot of boilerplate code to plumb down the arguments (especially if there are many arguments). If this class is purely for data, then dataclasses provide a much easier and less error prone alternative.

from dataclasses import dataclass

@dataclass
class a:
    name: str

@dataclass
class b(a):
    age: int

print(b('joe', 12))
b(name='joe', age=12)
Answered By: flakes
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.