Let's break down some most common scenario it one by one — all using BankAccount vibe
1. Multiple Objects using Constructor
class BankAccount:
def __init__(self, holder, balance):
self.holder = holder
self.balance = balance
acc1 = BankAccount("Maham", 1000)
acc2 = BankAccount("Ali", 1500)
acc3 = BankAccount("Zoya", 2000)
print(acc1.holder) # Maham
print(acc2.balance) # 1500
Each object gets its own memory.
Means → every time constructor runs fresh for every new object.
2. 👨👩👧👦 Inheritance with Constructor
Suppose now we have a child class called SavingsAccount:
class BankAccount:
def __init__(self, holder, balance):
self.holder = holder
self.balance = balance
class SavingsAccount(BankAccount):
def __init__(self, holder, balance, interest_rate):
super().__init__(holder, balance)
self.interest_rate = interest_rate
☕ What’s happening here?
-
SavingsAccountis inheriting fromBankAccount -
Inside child’s constructor, we used
super().__init__()
→ to call parent’s constructor
So now you can do:
acc4 = SavingsAccount("Maham", 5000, 0.05)
print(acc4.holder) # Maham
print(acc4.interest_rate) # 0.05
3. 🔁 Override Constructor in Subclass
You already saw this:
-
If child class defines its own constructor, it overrides the parent’s one
-
But… if you don’t use
super(), then parent’s constructor won’t run at all
class SavingsAccount(BankAccount):
def __init__(self, holder, interest_rate):
self.holder = holder
self.interest_rate = interest_rate
Now:
acc = SavingsAccount("Ali", 0.07)
print(acc.holder) # Ali
print(acc.interest_rate) # 0.07
print(acc.balance) # ❌ will give error
Because we didn’t call super() → balance never got created.
4.Using constructor with classmethods
Sometimes you want to create an object in a custom way
like from a string or a dictionary or after validation etc
For this → we use @classmethod to create alternative constructors
🏦 Example 1: Create from string
class BankAccount:
def __init__(self, holder, balance):
self.holder = holder
self.balance = balance
@classmethod
def from_string(cls, account_str):
holder, balance = account_str.split("-")
return cls(holder, float(balance))
acc = BankAccount.from_string("Maham-5000")
print(acc.holder) # Maham
print(acc.balance) # 5000.0
🧠 Wait… how this is useful?
-
helpful when you're getting data from APIs, files, forms etc
-
makes code cleaner
-
can hide complex logic inside
Example 2: Validating before creating
class BankAccount:
def __init__(self, holder, balance):
self.holder = holder
self.balance = balance
@classmethod
def create_if_valid(cls, holder, balance):
if balance < 0:
print("Invalid balance")
return None
return cls(holder, balance)
acc = BankAccount.create_if_valid("Maham", -100) # Invalid balance