Courses / Computer Science XII (HSSC-II) – FBISE Complete SLO-Based Course
3.2 Object-Oriented Programming in Python: Classes, Objects and State
Unit 3 – Programming Fundamentals · 100 min read · 9 MCQs to check yourself
Corey Schafer – Python OOP tutorial 1: classes and instances
1. Class, object, attributes and methods
| Term | Meaning | Example |
|---|---|---|
| Class | Blueprint/template | class BankAccount: |
| Object (instance) | A real thing made from the class | acc1 = BankAccount("Ali", 5000) |
| Instance attribute | Data stored in each object – its state | self.balance |
| Method | Function inside the class that uses or changes state | deposit(), withdraw() |
Constructor __init__ |
Runs automatically when an object is created; sets initial state | def __init__(self, owner, balance) |
self |
Refers to the current object | self.owner = owner |
class BankAccount:
bank_name = "PrepOasis Bank" # class attribute – shared by all objects
def __init__(self, owner, balance=0):
self.owner = owner # instance attributes = the object's state
self.balance = balance
self.history = []
def deposit(self, amount):
if amount <= 0:
print("Deposit must be positive")
return
self.balance += amount
self.history.append(("deposit", amount))
def withdraw(self, amount):
if amount > self.balance:
print(f"{self.owner}: insufficient funds")
return
self.balance -= amount
self.history.append(("withdraw", amount))
def __str__(self):
return f"{self.owner}: Rs {self.balance}"
ali = BankAccount("Ali", 5000)
sara = BankAccount("Sara")
ali.deposit(2000)
ali.withdraw(1500)
sara.deposit(800)
sara.withdraw(1000)
print(ali, "|", sara)
print(ali.history)
print(ali.bank_name, sara.bank_name)
Output:
Sara: insufficient funds
Ali: Rs 5500 | Sara: Rs 800
[('deposit', 2000), ('withdraw', 1500)]
PrepOasis Bank PrepOasis Bank
Each object keeps its own state: Ali’s balance changes without affecting Sara’s. The methods are the only way the program changes the balance – that is encapsulation.
2. Encapsulation and abstraction
- Encapsulation: keep data and the methods that work on it together and protect the data. In Python a leading underscore (
self._pin) means “internal – do not use from outside”; two underscores (self.__pin) make access harder (name mangling). - Abstraction: users of a class only need to know what methods do (
withdraw(500)), not how they work inside.
3. Inheritance – reuse a class
class SavingsAccount(BankAccount): # child class inherits everything
def __init__(self, owner, balance=0, rate=0.05):
super().__init__(owner, balance) # reuse the parent constructor
self.rate = rate
def add_profit(self):
self.deposit(round(self.balance * self.rate))
s = SavingsAccount("Bilal", 10000)
s.add_profit()
print(s, "| rate:", s.rate)
Output:
Bilal: Rs 10500 | rate: 0.05
4. Polymorphism – same method name, different behaviour
Polymorphism lets us use the same function or operator in different ways depending on the object.
class Shape:
def area(self):
return 0
class Rectangle(Shape):
def __init__(self, w, h):
self.w, self.h = w, h
def area(self):
return self.w * self.h
class Circle(Shape):
def __init__(self, r):
self.r = r
def area(self):
return round(3.14159 * self.r ** 2, 2)
for shape in [Rectangle(4, 5), Circle(3)]:
print(type(shape).__name__, shape.area()) # same call, different behaviour
print(2 + 3, "2" + "3", [1] + [2]) # + is polymorphic too
Output:
Rectangle 20
Circle 28.27
5 23 [1, 2]
5. Managing state – a practical example
class Student:
def __init__(self, name, roll_no):
self.name = name
self.roll_no = roll_no
self.marks = {} # state: subject -> mark
def add_mark(self, subject, mark):
self.marks[subject] = mark
def average(self):
return round(sum(self.marks.values()) / len(self.marks), 1) if self.marks else 0
def result(self):
return "Pass" if all(m >= 33 for m in self.marks.values()) else "Fail"
s1 = Student("Ayesha", 12)
s1.add_mark("CS", 88); s1.add_mark("Physics", 74); s1.add_mark("Maths", 91)
print(s1.name, s1.average(), s1.result())
Output:
Ayesha 84.3 Pass
Short and long questions
1. Write a Python program using Object-Oriented Programming to define a class BankAccount with instance attributes owner and balance to manage state. Include methods deposit(), withdraw() (which must not allow the balance to go negative) and display(). Create two objects and show how each keeps its own state. (6)
Model answer
class BankAccount:
def __init__(self, owner, balance=0):
self.owner = owner # instance attributes (state)
self.balance = balance
def deposit(self, amount):
if amount > 0:
self.balance += amount
def withdraw(self, amount):
if amount <= self.balance:
self.balance -= amount
else:
print("Insufficient funds")
def display(self):
print(self.owner, "balance:", self.balance)
a = BankAccount("Ali", 5000)
b = BankAccount("Sara", 1000)
a.deposit(2000) # Ali: 7000
b.withdraw(1500) # Insufficient funds – Sara stays 1000
a.withdraw(500) # Ali: 6500
a.display() # Ali balance: 6500
b.display() # Sara balance: 1000
Explanation: the class is the blueprint; __init__ sets each object’s initial state; deposit and withdraw are the only way to change balance (encapsulation) and withdraw checks the rule; objects a and b each keep their own balance, so changing one does not affect the other.
2. What is encapsulation? How is it achieved in Python?
Model answer
Encapsulation bundles data with the methods that operate on it and restricts direct access to internal data, so the object controls how its state changes.
In Python: keep data as attributes and change it only through methods (deposit()); mark internal attributes with _name (protected by convention) or __name (name-mangled “private”); use properties for controlled access.
3. Write a Python class Rectangle with instance attributes length and width and methods area() and perimeter().
Model answer
class Rectangle:
def __init__(self, length, width):
self.length = length
self.width = width
def area(self):
return self.length * self.width
def perimeter(self):
return 2 * (self.length + self.width)
r = Rectangle(5, 3)
print(r.area(), r.perimeter()) # 15 16
4. Explain inheritance with a Python example.
Model answer
Inheritance lets a child class reuse and extend the attributes and methods of a parent class.
class Person:
def __init__(self, name): self.name = name
def greet(self): return "Hello " + self.name
class Teacher(Person): # inherits greet()
def __init__(self, name, subject):
super().__init__(name)
self.subject = subject
t = Teacher("Ms Rozina", "CS"); print(t.greet())
5. What is polymorphism? Give a Python example.
Model answer
Polymorphism means the same method name or operator behaves differently for different objects/types.
class Dog:
def sound(self): return "Woof"
class Cat:
def sound(self): return "Meow"
for pet in [Dog(), Cat()]:
print(pet.sound()) # Woof, Meow
Also + adds numbers but joins strings.
6. Define class, object and instance attribute with a Python example.
Model answer
- Class: a blueprint that defines attributes and methods. Object: an instance created from a class. Instance attribute: data stored in each object (its state).
class Car:
def __init__(self, model, speed=0):
self.model = model # instance attributes
self.speed = speed
my_car = Car("Corolla") # object
This lesson ends with a quiz of 9 MCQs. Open the lesson on PrepOasis to take it and save your progress.
Previous: 3.1 Programming Paradigms: Procedural, Object-Oriented and Functional · Next: 3.3 Advanced Data Structures in Python: Lists, Nested Lists and Dictionaries
All lessons in Computer Science XII (HSSC-II) – FBISE Complete SLO-Based Course