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