__init__ & Instance Attributes
__init__ is the constructor — it runs automatically when you create an object. Use it to set up initial attributes.
15 min•By Priygop Team•Updated 2026
__init__ Constructor
__init__ Constructor
class BankAccount:
def __init__(self, owner, balance=0):
self.owner = owner
self.balance = balance
self.transactions = []
def deposit(self, amount):
if amount > 0:
self.balance += amount
self.transactions.append(f"+{amount}")
print(f"Deposited: {amount}. Balance: {self.balance}")
def withdraw(self, amount):
if 0 < amount <= self.balance:
self.balance -= amount
self.transactions.append(f"-{amount}")
print(f"Withdrawn: {amount}. Balance: {self.balance}")
else:
print("Insufficient funds!")
def summary(self):
print(f"\n=== {self.owner}'s Account ===")
print(f"Balance: ${self.balance}")
print(f"Transactions: {', '.join(self.transactions)}")
# Usage
acc = BankAccount("Alice", 1000)
acc.deposit(500)
acc.withdraw(200)
acc.withdraw(2000)
acc.summary()Tip
Tip
Initialize ALL attributes in __init__, even if they start empty. self.transactions = [] is better than creating it later.
Diagram
Loading diagram…
Classes are syntactic sugar over prototypes.
Common Mistake
Warning
Forgetting to call __init__ from subclass. Use super().__init__() to ensure parent initialization runs.
Practice Task
Note
(1) Build a BankAccount with deposit/withdraw. (2) Add balance validation. (3) Track transaction history in a list.