So far, you’ve written Python programs using variables, functions, loops, and lists this is called procedural programming.
But what if you want to:
- Represent real-world things like a
Car
,Student
, orBook
? - Reuse and organize your code better?
- Build scalable applications like games, dashboards, or web APIs?
That’s where Object-Oriented Programming (OOP) comes in.
In this post, we’ll cover:
- What OOP is and why it matters
- How to create and use classes and objects
🔗 Read this detailed explanation ofclasses and objects
in a dedicated post → - Instance variables vs methods
🔗 Read this detailed explanation ofInstance variables vs methods
in a dedicated post → - What is self in Python?
🔗 Read this detailed explanation ofself
in a dedicated post → - Constructors (
__init__
) - A real-world example
- Best practices and common mistakes
Let’s dive in.
🧠 What Is Object-Oriented Programming?
Object-Oriented Programming (OOP) is a way of writing programs using objects that combine:
- Data (variables like name, age, balance)
- Behavior (functions like withdraw, display, speak)
Think of it as creating your own custom data types.
🧱 What Is a Class?
A class is a blueprint for creating objects.
Python
class Student:
pass
🧍♂️ What Is an Object?
An object is an instance of a class it’s the actual thing based on the blueprint.
Python
s1 = Student() # s1 is an object of the Student class
🔧 __init__
Method – The Constructor
Let’s create a more useful class:
Python
class Student:
def __init__(self, name, age):
self.name = name
self.age = age
🔍 Breakdown:
__init__()
is a special method that runs when you create an objectself
refers to the object being createdname
andage
are input parametersself.name
creates a variable tied to the object
✅ Creating Objects from Class
Python
s1 = Student("Ali", 20)
s2 = Student("Fatima", 22)
print(s1.name) # Ali
print(s2.age) # 22
🎯 What is self
in Python?
Think of self
as:
- A label that refers to the current object
- Required as the first argument in all class methods
- Automatically passed when you call methods on the object
Python
class Example:
def say_hello(self):
print("Hello!")
e = Example()
e.say_hello() # No need to pass 'self' Python does that
🔁 Adding Methods (Functions Inside Classes)
Python
class Student:
def __init__(self, name, age):
self.name = name
self.age = age
def speak(self):
print(f"My name is {self.name}, and I'm {self.age} years old.")
Python
s1 = Student("Ali", 21)
s1.speak() # My name is Ali, and I'm 21 years old.
🎯 Class vs Instance Variables
Class Variable: Shared across all objects
Instance Variable: Unique per object
Python
class Student:
school = "PyUniverse" # Class variable
def __init__(self, name):
self.name = name # Instance variable
💡 Real-Life OOP Example: Bank Account
Python
class BankAccount:
def __init__(self, owner, balance=0):
self.owner = owner
self.balance = balance
def deposit(self, amount):
self.balance += amount
print(f"₹{amount} deposited. New balance: ₹{self.balance}")
def withdraw(self, amount):
if amount > self.balance:
print("Insufficient funds.")
else:
self.balance -= amount
print(f"₹{amount} withdrawn. Remaining balance: ₹{self.balance}")
Python
a1 = BankAccount("Sufiyan", 1000)
a1.deposit(500)
a1.withdraw(700)
🔁 Using __str__
to Print Objects Nicely
Python
class Product:
def __init__(self, name, price):
self.name = name
self.price = price
def __str__(self):
return f"{self.name} costs ₹{self.price}"
Python
p = Product("Keyboard", 899)
print(p) # Keyboard costs ₹899
⚠️ Common OOP Mistakes (and Fixes)
Mistake | Fix |
---|---|
Forgetting self in method params | Always write def method(self) |
Not using self.variable | Must use self.var_name inside class methods |
Mixing class and instance variables | Use self.var for unique, Class.var for shared values |
Trying to access variable before init | Always initialize inside __init__ |
More To Read On This Topic
- Encapsulation in Python: Data Hiding, __str__(), and Clean Class Design
- Learn Python Programming from Scratch: A Beginner’s Roadmap