Object-Oriented Programming (OOP) Part 1 – Classes, Objects, Attributes, Methods, and Encapsulation
Quick Answer: Object-Oriented Programming (OOP) groups data and actions together into classes and objects. A class is a blueprint, an object is a living instance, and encapsulation protects data from unwanted changes.
Imagine Priya manages a busy grocery shop in Bengaluru with 500 different stock items.
Every item needs a name, price, and stock count, along with functions to update inventory.
How would you write this cleanly without repeating variables for every single item?
1. Why Do We Need Object-Oriented Programming?
The problem without classes
We could write separate variables and functions for every item in the shop.
Example 1: Loose variables without a class
This approach works for two items, but it becomes messy very quickly.
item1_name = "Rice"
item1_price = 55.0
item1_stock = 120
item2_name = "Sugar"
item2_price = 42.0
item2_stock = 85
Expected output
Variables declared individually without structure
This code runs, but it has major design problems when your shop grows.
- Variables are disconnected, so item names and prices can easily get mismatched.
- Adding 500 items means creating 1,500 separate loose variables.
- There is no safe, reusable way to update stock quantities across items.
We need a single blueprint that groups data and behavior together.
2. The Solution: Classes and Objects
Class = a blueprint used to create objects.
Object = a real item created from a class blueprint.
Attribute = a variable stored inside an object.
Method = a function defined inside a class that performs an action.
Stock: 120
Stock: 85
Stock: 40
Figure 1: A single class definition builds multiple independent product objects in memory.
3. Writing Your First Class with Attributes
Let us write a Python class using the special __init__ constructor method.
Example 2: Initializing attributes with __init__
This code defines a class and creates two item objects with specific values.
class GroceryItem :
def __init__ (self , name, price, stock):
self .name = name
self .price = price
self .stock = stock
rice = GroceryItem ("Rice", 55.0 , 120 )
sugar = GroceryItem ("Sugar", 42.0 , 85 )
print(rice.name, rice.price, rice.stock)
print(sugar.name, sugar.price, sugar.stock)
Expected output
Rice 55.0 120 Sugar 42.0 85
Notice the self parameter represents the specific object being created.
Python passes self automatically when you call the class name.
4. Adding Methods for Object Behavior
Classes do more than hold data – they perform actions through methods.
Example 3: Adding stock update and billing methods
This code adds behavior inside the class to calculate totals and sell items.
class GroceryItem :
def __init__ (self , name, price, stock):
self .name = name
self .price = price
self .stock = stock
def sell (self , quantity):
if quantity <= self .stock:
self .stock -= quantity
return quantity * self .price
return "Out of stock"
item = GroceryItem ("Rice", 55.0 , 10 )
bill = item.sell (3 )
print("Bill amount:", bill)
print("Remaining stock:", item.stock)
Expected output
Bill amount: 165.0 Remaining stock: 7
The sell method updates internal stock and calculates the total price safely.
5. Encapsulation and Protecting Data
Encapsulation = hiding internal object data so it cannot be changed directly from outside.
In Python, we use a leading double underscore like __stock to make an attribute private.
Example 4: Using private attributes and getter methods
This code prevents direct external manipulation of sensitive stock numbers.
class SecureItem :
def __init__ (self , name, stock):
self .name = name
self .__stock = stock # Private attribute
def get_stock (self ):
return self .__stock
def add_stock (self , amount):
if amount > 0 :
self .__stock += amount
item = SecureItem ("Sugar", 50 )
item.add_stock (20 )
print("Current stock:", item.get_stock ())
Expected output
Current stock: 70
Directly accessing item.__stock from outside will raise an AttributeError.
Controlled access protects object state from invalid updates.
| Procedural Approach | Object-Oriented Approach |
|---|---|
| Separate variables and standalone functions | Data and methods bundled inside classes |
| Hard to manage data validation | Encapsulation protects internal state |
| Difficult to scale for 500+ items | Easy instantiation of thousands of objects |
The important terms to remember
- Class = a blueprint for creating objects.
- Object = an instance of a class with unique data.
- Attribute = a variable attached to an object.
- Method = a function defined inside a class.
- Encapsulation = restricting direct access to internal data.
Design tip: Always use getter and setter methods to inspect or modify private attributes safely.
6. Common Mistakes to Avoid
1. Forgetting the self parameter in methods
Writing class methods without self as the first parameter causes Python to raise a TypeError when called.
Better approach: Always include self as the first argument in all instance methods and constructors.
7. Interview Questions & Answers
Question 1: What is the purpose of the __init__ method in Python?
What the interviewer expects: A clear explanation of constructor initialization.
Strong answer: "The __init__ method is a constructor that Python runs automatically when you create a new object. We use it to assign initial values to object attributes, such as setting the name and price of an item in Priya's shop."
What interviewers expect at different levels
- Junior developer: Knows how to write classes, constructors, and instance methods.
- Senior developer: Understands private attribute name mangling and memory references.
- Technical architect: Focuses on domain modeling, encapsulation boundaries, and state safety.
8. Practice Exercises
Beginner: Library book record
Create a Book class with title, author, and is_available attributes, plus a method to borrow the book.
Expected result: Borrowing updates availability status correctly.
Intermediate: Bank account security
Build a BankAccount class with private balance encapsulation and deposit/withdrawal validation rules.
Hint: Reject withdrawals exceeding the current balance.
9. Frequently Asked Questions (FAQ)
Is everything in Python an object?
Yes. Integers, strings, functions, and classes are all treated as first-class objects in Python.
Can you add attributes to an object outside the class?
Yes, Python allows dynamic attribute creation, though it is generally discouraged for clean architecture.
10. Next Steps
Now that you have mastered classes, objects, and encapsulation, you are ready to learn about inheritance, polymorphism, and dunder methods in Part 2.