Classes and objects are the foundation of Object-Oriented Programming (OOP).
They help you structure your code in a clean, reusable, and organized way.
WHAT IS A CLASS?
A class is a blueprint or template used to create objects.
It defines:
- Attributes (variables)
- Methods (functions)
Example of a Class
class Car:
pass
This is a simple class named Car.
WHAT IS AN OBJECT?
An object is an instance of a class.
It represents a real-world entity created from a class.
class Car:
passcar1 = Car()
print(type(car1))
Here, car1 is an object of the Car class.
CLASS WITH ATTRIBUTES (USING CONSTRUCTOR)
The constructor method __init__() initializes object data.
class Car:
def __init__(self, brand, color):
self.brand = brand
self.color = colorcar1 = Car("Toyota", "White")
print(car1.brand)
print(car1.color)
Explanation:
__init__runs automatically when object is createdselfrefers to the current objectbrandandcolorare attributes
CLASS WITH METHODS
Methods are functions defined inside a class.
class Car:
def __init__(self, brand):
self.brand = brand def start(self):
print(self.brand, "car is starting.")car1 = Car("Honda")
car1.start()
Here:
start()is a method- It uses object data
MULTIPLE OBJECTS
You can create many objects from one class.
car1 = Car("Toyota")
car2 = Car("BMW")car1.start()
car2.start()
Each object has its own data.
REAL-WORLD ANALOGY
Class = Blueprint of a house
Object = Actual house built from that blueprint
Class = Student
Objects = Hira, Ali, Ahmed
KEY DIFFERENCE
| Class | Object |
|---|---|
| Blueprint | Instance |
| Defined once | Created multiple times |
WHY USE CLASSES AND OBJECTS?
• Organize large programs
• Make reusable code
• Model real-world systems
• Improve maintainability
KEY TAKEAWAY
A class defines structure and behavior.
An object is a real instance created from that class.
Understanding classes and objects is the first major step in mastering OOP in Python.