Inheritance
Definition: Inheritance is a core mechanism in Object-Oriented Programming (OOP) that allows a new class (called a child or subclass) to adopt and reuse the attributes and methods of an existing class (called a parent or superclass).
Why: Inheritance prevents code duplication. Instead of rewriting the exact same functions for different but related entities, you define the shared behavior once in a parent class, and let child classes automatically inherit it and add their own unique features.
The Hierarchy Relationship
- Parent Class (Superclass / Base Class): The existing class whose features are being passed down.
- Child Class (Subclass / Derived Class): The new class that inherits features from the parent class.
Example
# Parent Class
class Person:
def speak(self):
print("Hello")
# Child Class (Inherits from Person)
class Student(Person):
pass
# Creating an instance of the Child Class
s = Student()
# The Student object can use methods from the Person class
s.speak() # Output: Hello
Explanation
- Passing the Parent Class: By placing
Personinside the parentheses during the definition of the student class (class Student(Person):), we establish the inheritance link. - Reusing Logic: Even though the
Studentclass is completely empty (using only thepasskeyword), an object created from it (s) automatically gains access to thespeak()method defined up in thePersonclass.
Extending Functionality (Method Overriding)
A child class isn't strictly locked into doing exactly what its parent does. If a child class needs to change how a specific method works, it can redefine that method with the same name. This is known as **Method Overriding**:
class Teacher(Person):
# Overriding the parent's speak method
def speak(self):
print("Good morning, class!")
t = Teacher()
t.speak() # Output: Good morning, class! (Uses the child's version, not the parent's)
Key Notes
- Inheritance represents an **"is-a" relationship**. For example, a
Studentis aPerson, aCaris aVehicle. - To call a method from the parent class explicitly inside an overridden child method, you can use Python's built-in
super()function (e.g.,super().speak()). - Python supports **Multiple Inheritance**, which means a child class can inherit features from more than one parent class at the same time (e.g.,
class Child(Parent1, Parent2):).
Executing...
❌ Error:
✅ Output:
// Click Run ▶ to execute