Python Inheritance
gocourse.in Maintenance

We'll be back soon

Our CDN (cdn.gocourse.in) is currently unreachable. Some images, JavaScript, or CSS files may not load properly.

Estimated downtime: ~30 minutes

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:

Name: Aarav Department: IT

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:

Name: Neha Department: HR

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:

Name: Neha Department: HR

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():

Name: Neha Department: HR

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:

Team Size: 8

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:

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

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