Python
Python Basics
- Introduction to Python and Its History
- Python Syntax and Indentation
- Python Variables and Data Types
- Dynamic and Strong Typing
- Comments and Docstrings
- Taking User Input (input())
- Printing Output (print())
- Python Operators (Arithmetic, Logical, Comparison)
- Type Conversion and Casting
- Escape Characters and Raw Strings
Data Structures in Python
- Lists
- Dictionaries
- Dictionary Comprehensions
- Strings and String Manipulation
- Tuples
- Python Sets: Unordered Collections
- List Comprehensions and Generator Expressions
- Set Comprehensions
- String Formatting
- Indexing and Slicing
Control Flow and Loops
- Conditional Statements: if, elif, and else
- Loops and Iteration
- While Loops
- Nested Loops
- Loop Control Statements
- Iterators and Iterables
- List, Dictionary, and Set Iterations
Functions and Scope
- Defining and Calling Functions (`def`)
- Function Arguments (`*args`, `**kwargs`)
- Default Arguments and Keyword Arguments
- Lambda Functions
- Global and Local Scope
- Function Return Values
- Recursion in Python
Object-Oriented Programming (OOP)
- Object-Oriented Programming
- Classes and Objects
- the `__init__()` Constructor
- Instance Variables and Methods
- Class Variables and `@classmethod`
- Encapsulation and Data Hiding
- Inheritance and Subclasses
- Method Overriding and super()
- Polymorphism
- Magic Methods and Operator Overloading
- Static Methods
- Abstract Classes and Interfaces
Python Programs
- Array : Find median in an integer array
- Array : Find middle element in an integer array
- Array : Find out the duplicate in an array
- Array : Find print all subsets in an integer array
- Program : Array : Finding missing number between from 1 to n
- Array : Gap and Island problem
- Python Program stock max profit
- Reverse words in Python
- Python array duplicate program
- Coin change problem in python
- Python Write fibonacci series program
- Array : find all the pairs whose sum is equal to a given number
- Find smallest and largest number in array
- Iterate collections
- List comprehensions
- Program: Calculate Pi in Python
- String Formatting in Python
👨👩👧 Inheritance and Subclasses in Python
In object-oriented programming (OOP), inheritance is a powerful concept that allows you to create a new class from an existing one. This helps you reuse code, build a hierarchical structure, and make your programs more efficient and organized.
Python supports inheritance naturally, making it easy for beginners to apply OOP principles without complex syntax.
🔄 What is Inheritance?
Inheritance allows a child class (subclass) to inherit attributes and methods from a parent class (superclass). This means the subclass can access the functionality of the superclass without rewriting the same code.
📌 Why use inheritance?
- ✅ Promotes code reusability
- ✅ Reduces duplication
- ✅ Helps model real-world hierarchies
- ✅ Makes code more readable and manageable
🧓 Superclass and 👶 Subclass
Here’s a basic example:
# Parent classclass Animal: def speak(self): print("Animal speaks")
# Child classclass Dog(Animal): pass
d = Dog()d.speak() # Output: Animal speaks
In this example:
Animal
is the superclass.Dog
is the subclass and inherits thespeak()
method fromAnimal
.
Even though Dog
has no code, it can use everything from Animal
.
📚 Creating a Subclass in Python
To create a subclass, just pass the parent class name in parentheses:
class Parent: pass
class Child(Parent): pass
This means Child
inherits everything from Parent
.
🧠 Inheriting Methods and Attributes
You can inherit and extend methods or properties:
class Animal: def __init__(self, name): self.name = name
def speak(self): print(f"{self.name} makes a sound")
class Cat(Animal): def purr(self): print(f"{self.name} is purring")
c = Cat("Whiskers")c.speak() # Output: Whiskers makes a soundc.purr() # Output: Whiskers is purring
The Cat
class can now use both speak()
and its own method purr()
.
🔄 Overriding Parent Methods
A child class can override methods from the parent:
class Animal: def speak(self): print("Animal makes a sound")
class Dog(Animal): def speak(self): print("Dog barks")
d = Dog()d.speak() # Output: Dog barks
By redefining speak()
in Dog
, the parent’s version is replaced for that subclass.
🪜 The super()
Function
When you override a method, but still want to call the parent version, use the super()
function:
class Animal: def speak(self): print("Animal makes a sound")
class Dog(Animal): def speak(self): super().speak() print("Dog barks")
d = Dog()d.speak()# Output:# Animal makes a sound# Dog barks
This is helpful when you want to extend—not replace—the parent method.
🔁 Types of Inheritance in Python
Python supports different types of inheritance:
1. Single Inheritance
One child inherits from one parent.
class A: pass
class B(A): pass
2. Multiple Inheritance
One child inherits from multiple parents.
class A: pass
class B: pass
class C(A, B): pass
Python uses Method Resolution Order (MRO) to handle such cases.
3. Multilevel Inheritance
A class inherits from a subclass which inherits from another class.
class A: pass
class B(A): pass
class C(B): pass
4. Hierarchical Inheritance
Multiple child classes inherit from the same parent.
class A: pass
class B(A): pass
class C(A): pass
🛠 Real-World Example
Let’s create a vehicle hierarchy:
class Vehicle: def __init__(self, brand): self.brand = brand
def start(self): print(f"{self.brand} is starting")
class Car(Vehicle): def wheels(self): print("Car has 4 wheels")
class Bike(Vehicle): def wheels(self): print("Bike has 2 wheels")
c = Car("Toyota")b = Bike("Yamaha")
c.start() # Toyota is startingc.wheels() # Car has 4 wheels
b.start() # Yamaha is startingb.wheels() # Bike has 2 wheels
This shows how subclasses can share common methods (start
) while also having their own unique behavior (wheels
).
📏 Best Practices
✅ Use inheritance when classes have a “is-a” relationship
✅ Keep your base classes generic, and child classes specific
✅ Avoid deep inheritance chains—they can get confusing
✅ Favor composition over inheritance when appropriate
✅ Use super()
correctly to enhance extensibility
🤔 When Not to Use Inheritance
Inheritance is powerful, but not always necessary. Avoid it if:
- There’s no clear hierarchical relationship
- You’re only reusing a few methods—use composition instead
- You want more flexibility between components
🔁 Composition vs Inheritance (Quick Comparison)
Feature | Inheritance | Composition |
---|---|---|
Relation | ”Is-a" | "Has-a” |
Reusability | Reuses base class code | Reuses other class logic |
Flexibility | Less flexible | More flexible |
Coupling | Tightly coupled | Loosely coupled |
✅ Summary
Inheritance in Python allows classes to share functionality in an organized and hierarchical way. It’s a foundational concept in object-oriented programming that promotes clean, reusable, and scalable code.
👇 Key Takeaways:
- Inheritance lets one class derive features from another.
- Subclasses can override or extend superclass behavior.
- Use
super()
to access parent methods safely. - Python supports single, multiple, multilevel, and hierarchical inheritance.
- Don’t overuse inheritance—apply it wisely with real-world structure in mind.