Python Inheritance

Python Inheritance

Kishore V


Python Inheritance

Inheritance is a core concept in Python that allows one class to reuse the properties and behaviors of another class. It helps reduce code duplication and makes programs easier to manage.

  • Base Class (Parent Class): The class whose features are inherited.
  • Derived Class (Child Class): The class that receives properties and methods from another class.

Creating a Base Class

Any normal Python class can act as a base class.

Example

Create a base class named Employee with name and department attributes and a method to display details:

Output:

Name: Aarav
Department: IT
Try it Yourself

Creating a Derived Class

To create a child class, pass the base class name inside parentheses during class creation.

Example

Create a class Manager that inherits from the Employee class:

Output:

Name: Neha
Department: HR
Try it Yourself

Note: Use the pass keyword when you don’t want to add any new properties or methods. Now, the Manager class can use everything from the Employee class.

Adding an __init__() Method to the Child Class

When you define an __init__() method inside the child class, it overrides the parent’s constructor.

Example

Add an __init__() method to the Manager class:

Output:

Name: Neha
Department: HR
Try it Yourself

Calling the parent’s __init__() ensures the inherited attributes are initialized correctly.

Using the super() Function

Python provides the super() function to make inheritance cleaner and more readable.

Example

Rewrite the previous constructor using super():

Output:

Name: Neha
Department: HR
Try it Yourself

Using super() removes the need to explicitly mention the parent class name.

Adding New Properties to the Child Class

A child class can have its own additional properties.

Example

Add a team_size property to the Manager class:

Output:

Team Size: 8
Try it Yourself

Adding New Methods to the Child Class

You can also define methods that exist only in the child class.

Example

Add a greet_team() method to the Manager class:

Output:

Hello, I am Rohan from Finance department managing a team of 8 members.
Try it Yourself

Our website uses cookies to enhance your experience. Learn More
Accept !