Multiple Inheritance

🤹‍♀️ Multiple Inheritance Example

class RewardSystem:
    def apply_reward(self):
        print("Reward applied")

class BankAccount:
    def __init__(self):
        self.balance = 0

    def deposit(self, amt):
        self.balance += amt
        print(f"Deposited {amt}")

class PremiumAccount(BankAccount, RewardSystem):
    def bonus(self):
        self.apply_reward()
        print("Bonus for premium user")
acc = PremiumAccount()
acc.deposit(2000)      # from BankAccount
acc.apply_reward()     # from RewardSystem
acc.bonus()            # from PremiumAccount

🎯 This is multiple inheritance:

  • PremiumAccount got things from both BankAccount and RewardSystem

  • Python resolves order using MRO (method resolution order) internally


⚠️ Be careful with same method names in parents

class A:
    def say(self):
        print("A says hi")

class B:
    def say(self):
        print("B says hello")

class C(A, B):
    pass

obj = C()
obj.say()  # Output: A says hi (A comes first in inheritance list)

💡 Python follows the left-to-right rule (MRO) → A comes first


in this case:

class PremiumAccount(BankAccount, RewardSystem):
    def bonus(self):
        self.apply_reward()
        print("Bonus for premium user")

you don’t have to define a constructor
→ because PremiumAccount will automatically inherit the constructor from BankAccount (which comes first)

but...


🔍 if you want to add extra stuff, then yes you define it:

class PremiumAccount(BankAccount, RewardSystem):
    def __init__(self):
        super().__init__()  # calling BankAccount’s constructor
        self.status = "Premium"

super() calls first parent (BankAccount)
self.status adds child-level stuff


⚠️ if you don’t call super().__init__(), then parent properties won’t come
so use super() if you're overriding __init__ and still need parent values


Updated on