Inheritance

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

Updated on