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:
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:
Note: Use the
pass keyword
when you don’t want to add any new properties or methods directly to the
class body.
Adding an __init__() Method to the Child Class
When you define an
__init__()
method inside the child class, it overrides the parent’s constructor.
Calling the parent’s
__init__()
explicitly ensures the inherited attributes are initialized correctly.
Example
Using the super() Function
Python provides the
super()
function to make inheritance cleaner and more readable. Using
super()
removes the need to explicitly mention the parent class name.
Example
Adding New Properties to the Child Class
A child class can have its own additional properties that the parent class does not possess.
Example
Add a
team_size
property to the
Manager
class:
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:
