In object-oriented programming, inheritance allows a class to inherit attributes and methods from another class. This promotes code reuse and hierarchical relationships between classes.
Key Concepts
- Parent Class: The base class from which other classes inherit.
- Child Class: The class that inherits from a parent class.
- Method Overriding: Replacing a parent class method with a child class implementation.
- Super() Function: Used to call parent class methods from the child class.
Syntax Example
class Parent:
def __init__(self, name):
self.name = name
def greet(self):
return f"Hello from {self.name}"
class Child(Parent):
def __init__(self, name, age):
super().__init__(name) # Call parent constructor
self.age = age
def greet(self):
return f"Hi, I'm {self.name} and {self.age} years old!"
Use Cases
- Creating a hierarchy of classes (e.g.,
Animal
→Dog
,Cat
) - Implementing common functionality in a base class
- Extending functionality specific to subclasses
Real-World Application
For deeper understanding of related OOP concepts like polymorphism, check our tutorial: /en/courses/Python_Tutorials/polymorphism