What is Inheritance?
-
One class (child) inherits properties/methods from another class (parent)
-
Child can reuse, extend or override the parent
π¦ Example: Bank Account types
class BankAccount:
def __init__(self, holder, balance):
self.holder = holder
self.balance = balance
def show(self):
print(f"{self.holder} has balance {self.balance}")
class SavingsAccount(BankAccount):
def __init__(self, holder, balance, interest):
super().__init__(holder, balance)
self.interest = interest
def show(self):
print(f"{self.holder} (Savings) - Balance: {self.balance}, Interest: {self.interest}")
acc = SavingsAccount("Maham", 5000, 0.05)
acc.show()
# Maham (Savings) - Balance: 5000, Interest: 0.05
π§ Key things:
-
super()β used to call the parent constructor or methods -
Child class can override methods from parent class
-
You can access parentsβ methods using
super().method_name()
π€ Real-life analogies:
-
Parent class is like general blueprint
Child class is like special version with more features
jaise:-
VehicleβCar,Bike,Truck -
EmployeeβManager,Intern
-