Classes & Objects
Data Structures & Algorithms · First Steps · Basics · 18 min
Write your own classes: __init__, self, methods, encapsulation and inheritance, and understand the abstract data type idea behind every 'design a ...' interview question.
A class is a cookie cutter; objects are the cookies. Every cookie has the same shape, but each one can have its own sprinkles.
The idea in everyday words
An architect draws ONE blueprint for a house. A builder can use it to build fifty houses on different streets. Each house has its own address, paint colour and furniture, but they all have the same rooms and the same light switches. The blueprint is the class, each house is an object, and the light switches are the methods you are allowed to press.
Class = blueprint, object = thing built from it
So far you have used objects other people designed: lists have append, strings have upper. A class lets you design your own kind of object.
- Class: the blueprint. It says what data each object holds and what it can do.
- Object (or instance): one real thing built from the blueprint.
- Attribute: a piece of data stored on the object (
acct.balance). - Method: a function that belongs to the class (
acct.deposit(10)).
class Account:
def __init__(self, owner, balance=0):
self.owner = owner
self.balance = balance
def deposit(self, amount):
self.balance += amount
ana = Account("Ana")
bo = Account("Bo", 50)
ana.deposit(30)
print(ana.balance, bo.balance) # 30 50: each object has its own balance
__init__ and self, demystified
When you call Account("Ana"), Python does three things:
- Creates a new, empty object.
- Calls
__init__on it, passing the new object in asselfplus your arguments. - Hands the finished object back to you.
self simply means "the object this method is working on right now". When you write ana.deposit(30), Python actually runs Account.deposit(ana, 30). So inside deposit, self is ana.
That is why you must write self.balance and not just balance: a bare balance would be a temporary local variable that vanishes when the method ends.
| You write | Python runs |
|---|---|
ana = Account("Ana") |
new object, then Account.__init__(obj, "Ana") |
ana.deposit(30) |
Account.deposit(ana, 30) |
bo.deposit(5) |
Account.deposit(bo, 5) |
Encapsulation: methods guard the rules
Encapsulation means the object keeps its data and the rules about that data together, and outsiders go through the methods.
Why bother? Because rules live in one place. If "a balance can never go negative" is checked inside withdraw, nobody can forget to check it.
class Account:
def __init__(self, owner):
self.owner = owner
self._balance = 0 # leading underscore: "private, please don't touch"
def deposit(self, amount):
if amount > 0:
self._balance += amount
def withdraw(self, amount):
if amount <= 0 or amount > self._balance:
return False # rule enforced in ONE place
self._balance -= amount
return True
def balance(self):
return self._balance
acct = Account("Ana")
acct.deposit(40)
print(acct.withdraw(100), acct.withdraw(-50), acct.balance())
Notice the amount <= 0 check. Without it, withdraw(-50) would do balance - (-50) and secretly ADD 50. Guards like this are exactly what a method is for.
Python does not truly lock attributes. A leading underscore is a polite convention meaning "internal detail, use the methods".
Inheritance: reuse, then specialise
Inheritance lets a new class start with everything an existing class has, then add or change a few things. Write the parent in brackets: class Savings(Account).
class Account:
def __init__(self, owner, balance=0):
self.owner = owner
self.balance = balance
def deposit(self, amount):
self.balance += amount
class Savings(Account):
def __init__(self, owner, balance, rate):
super().__init__(owner, balance) # let the parent set up its part
self.rate = rate
def add_interest(self):
self.deposit(self.balance * self.rate // 100)
sam = Savings("Sam", 200, 10)
sam.deposit(100) # inherited from Account
sam.add_interest() # Savings' own method
print(sam.balance)
Method lookup: for sam.deposit, Python searches Savings first, then its parent Account, and uses the first match. Inheritance flows down only: a plain Account does not get add_interest.
Use inheritance for a real "is a" relationship (a Savings account is an Account). If it is "has a", store the other object as an attribute instead.
Abstract data types: the menu vs the kitchen
An abstract data type (ADT) describes what operations a structure offers and what they mean, without saying how they are done.
- Interface (the menu):
push(x),pop(),peek(),is_empty(). "pop gives back the most recently pushed item." - Implementation (the kitchen): a Python list, a linked list, a fixed array... The customer does not care, as long as the menu works.
class Stack:
def __init__(self):
self._items = [] # implementation detail
def push(self, x):
self._items.append(x)
def pop(self):
return self._items.pop()
def peek(self):
return self._items[-1]
def is_empty(self):
return len(self._items) == 0
s = Stack()
s.push(1); s.push(2)
print(s.pop(), s.peek(), s.is_empty())
This is the whole idea of the DSA course: stack, queue, map, priority queue are ADTs, and each lesson shows clever implementations with different speeds. In interviews, "Design a parking lot / LRU cache / Min Stack" means: pick the interface, then pick an implementation that makes each method fast.
Step by step
- Define the class:
class Account: with init, deposit and withdraw. Nothing exists yet, only the blueprint.
- ana = Account("Ana"):
A new empty object is made, init runs with self = that object: self.owner = 'Ana', self.balance = 0.
- bo = Account("Bo", 50):
A second, separate object: owner 'Bo', balance 50. Same blueprint, different data.
- ana.deposit(30):
Python runs Account.deposit(ana, 30). self is ana, so ana.balance goes 0 → 30. bo is untouched.
- bo.withdraw(80):
80 > 50, so the method refuses and returns False. The rule lives inside the class, so it cannot be skipped.
- bo.withdraw(20):
20 ≤ 50, so bo.balance becomes 30 and the method returns True.
Code example
class Account:
def __init__(self, owner, balance=0):
self.owner = owner
self.balance = balance
def deposit(self, amount):
self.balance += amount
def withdraw(self, amount):
if amount <= 0 or amount > self.balance:
return False
self.balance -= amount
return True
def __repr__(self):
return "Account(" + self.owner + ", " + str(self.balance) + ")"
class Savings(Account):
def __init__(self, owner, balance, rate):
super().__init__(owner, balance)
self.rate = rate
def add_interest(self):
self.deposit(self.balance * self.rate // 100)
ana = Account("Ana")
bo = Account("Bo", 50)
ana.deposit(30)
print(ana, bo)
print("bo withdraws 80:", bo.withdraw(80))
print("bo withdraws 20:", bo.withdraw(20), bo)
sam = Savings("Sam", 200, 10)
sam.deposit(100)
sam.add_interest()
print(sam, "is an Account?", isinstance(sam, Account))Interview tips
For any 'Design X' question, start by writing the method signatures and what each one promises. Agree on the interface before coding.
State the complexity of each method of your class, e.g. 'push O(1), get_min O(1) because I store the running minimum'.
Expect follow-ups. 'What if two threads call withdraw at once?' is a race condition: both can pass the balance check before either subtracts. The answer is a lock (or an atomic check-and-subtract, or a database transaction) around the check and the subtraction. Encapsulation helps because that lock lives in one method. 'How would you add a new account type?' is where inheritance comes in.
Prefer composition ('has a') over deep inheritance trees; say so if asked about trade-offs.
Challenge: Bank Account Simulator
Implement an Account class (balance starts at 0) with two methods:
deposit(amount): addamount, but ignore it ifamount <= 0.withdraw(amount): subtractamount, but refuse (change nothing) ifamount <= 0oramountis more than the balance.
Then write run_account(ops): create one account, apply each operation [name, amount] in order, and return the list of balances after each operation.
Example: run_account([["deposit", 50], ["withdraw", 20], ["withdraw", 100], ["deposit", 5]]) → [50, 30, 30, 35]
Solve it in the browser with tests, hints and an AI coach.
Practice problems
- Design Parking System (Easy)
- Implement Queue using Stacks (Easy)
- Design HashSet (Easy)
- Min Stack (Medium)
More in First Steps
- Coding from Zero
- Think Like a Programmer
- Python Crash Course for DSA
- Functions, Lists & Strings
- Big-O: How Fast Is My Code?
- Recursion
Previous: Functions, Lists & Strings · Next: Big-O: How Fast Is My Code?