How to Add __init__() Function to Child Class in Python


In this example, we will learn how to add the __init__() function to the child class in Python.

Source Code

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def print_person_info(self):
        print('name:', self.name, 'age:', self.age)


class Student(Person):
    def __init__(self, name, age):
        Person.__init__(self, name, age)     # to keep the inheritance of the parent's __init__() function


s = Student('John', 15)     # create an object
s.print_person_info()      # execute the print_person_info method

Output:

name: John age: 15
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
Advertisement