top of page

Inheritance in Python

Updated: Apr 19, 2023

Python supports inheritance.




The parent class properties and methods are inherited by the child class.



class Teacher:
    
    def __init__(self, name, school):
        self.name = name
        self.school = school
        
    def __str__(self):
        return f"{self.name} - {self.school}"
        
    def teach(self):
        print(self.school)
        


The parent class name should be specified inside the () brackets next to the child class name.


If the pass keyword is present just below the class name, then all the properties and methods of the parent class are inherited by the child class.




class Student1(Teacher):
    pass


When there is an __init__ method inside a child class, the child class does not inherit the parent class properties.



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


Using the super(), the parent class’ __init__ method can be used to inherit all its properties and methods.



class Student3(Teacher):
    def __init__(self, name, school):
        super().__init__(name, school)    

t1 = Teacher("ABC", "CDE")
print(t1)

s1 = Student1("Super", "MNO")
s1.teach()

s2 = Student2("JKL", 20)
print(s2.age)

s3 = Student3("XYZ", "Metric Coder")
print(s3)

The link to the Github repository is here .

0 views

Related Posts

How to Install and Run Ollama on macOS

Ollama is a powerful tool that allows you to run large language models locally on your Mac. This guide will walk you through the steps to...

bottom of page