Python Classes and Objects Explained
Python is an object-oriented programming (OOP) language, which means it allows you to build programs around classes and objects a clean, organized way to structure code for real-world applications.
If you're new to OOP, don’t worry, this guide walks you from the basics to several powerful OOP features, all explained in simple language with updated examples.
🔷 What is a Class?
A class is a blueprint for creating objects. It defines what details (attributes) and actions (methods) the object will have.
Think of a class like the architectural design of a house. It describes the structure, but it’s not the house itself. From the blueprint, you can build many houses—just like you can create multiple objects from one class.
Example:
class Laptop:
# attributes and methods will be added later
pass
🔷 What is an Object?
An object is a real instance created from a class. Just like a real house built from a design, an object is the actual usable form of a class.
Example:
my_device = Laptop()
Here, my_device becomes an object of the Laptop class.
🔷 Creating a Class with Attributes & Methods
Let’s build a more meaningful example—a Student class that stores name and grade, and displays a message.
class Student:
def __init__(self, name, grade):
self.name = name # instance attribute
self.grade = grade # instance attribute
def introduce(self):
print(f"I am {self.name} and I scored {self.grade} marks.")
# creating objects
s1 = Student("Aarav", 88)
s2 = Student("Mina", 92)
s1.introduce()
s2.introduce()
Output:
I am Aarav and I scored 88 marks.
I am Mina and I scored 92 marks.
🔷 Understanding the Parts
| Code Element | Meaning |
|---|---|
class Student: |
Defines a new class named Student |
__init__ |
Constructor that runs when an object is created |
self |
Refers to the current object |
self.name = name |
Creates an attribute inside the object |
introduce() |
A method that performs an action |
🔶 Instance vs Class Variables
In Python, attributes can be of two main types:
- Instance variables → unique to each object
- Class variables → shared by all objects of the class
Example:
class User:
company = "TechNova" # class variable
def __init__(self, username):
self.username = username # instance variable
u1 = User("dev_user")
u2 = User("admin_user")
print(u1.company) # TechNova
print(u2.company) # TechNova
🔶 Encapsulation & Private Attributes
Encapsulation means protecting internal data. Python allows pseudo-private variables using:
_var→ protected (convention)__var→ private (name-mangled)
Example:
class Account:
def __init__(self, owner, balance):
self.owner = owner
self.__balance = balance # private variable
def show_balance(self):
print(f"Balance: {self.__balance}")
🔶 Advanced OOP: Magic Methods (`__str__` & `__repr__`)
Magic methods give classes extra behavior. Two common ones:
__str__()→ user-friendly string__repr__()→ developer-friendly representation
Example:
class Book:
def __init__(self, title, price):
self.title = title
self.price = price
def __str__(self):
return f"{self.title} - ₹{self.price}"
b = Book("Intro to Python", 450)
print(b)
Output:
Intro to Python - ₹450
🔷 Practical Example: A Simple Order System
class Order:
tax_rate = 0.05 # class variable
def __init__(self, item, quantity, price):
self.item = item
self.quantity = quantity
self.price = price
def total_cost(self):
cost = self.quantity * self.price
return cost + (cost * Order.tax_rate)
order1 = Order("USB Cable", 3, 150)
print(order1.total_cost())
Output:
472.5
🔷 Updated Bank Account Example
class BankAccount:
def __init__(self, owner, balance):
self.owner = owner
self.balance = balance
def deposit(self, amount):
self.balance += amount
print(f"{amount} added. New balance: {self.balance}")
def withdraw(self, amount):
if amount <= self.balance:
self.balance -= amount
print(f"{amount} withdrawn. New balance: {self.balance}")
else:
print("Transaction denied! Not enough funds.")
acc = BankAccount("Sophia", 2500)
acc.deposit(800)
acc.withdraw(1200)
acc.withdraw(3000)
Output:
800 added. New balance: 3300
1200 withdrawn. New balance: 2100
Transaction denied! Not enough funds.
🔷 Summary
- A class is a blueprint; an object is an instance of that blueprint.
__init__initializes object attributes.selfrefers to the current object.- Instance variables → unique; class variables → shared.
- Encapsulation protects data.
- Magic methods make classes more readable and powerful.
- OOP helps keep code modular, reusable, and scalable.
❓ Frequently Asked Questions (FAQ)
1. Is Python fully object-oriented?
Python supports OOP fully but also allows procedural and functional styles.
2. Why do we use self?
It represents the instance calling the method and allows access to attributes and methods inside the class.
3. Can a class have multiple constructors?
Python does not support multiple constructors directly, but you can use default values or class methods.
4. Are private variables truly private?
No, but Python uses name-mangling to protect internal attributes.
5. What is the difference between a class and an object?
Class = design / blueprint; Object = real implementation of that design.
📢 Your turn:
Now that you understand Python classes and objects including advanced concepts, try creating your own mini project.
Here are some ideas:
- Student grade calculator
- Simple inventory management
- Library book tracking system
- Online shopping cart
Keep practicing OOP is the backbone of professional Python development.