In Python, Classes and Objects are the core components of Object-Oriented Programming (OOP). While procedural programming focuses on writing functions or blocks of code that perform computations, OOP focuses on creating "objects" that contain both data and behavior.
A Class is a blueprint or a template for creating objects. It defines a set of attributes (data) and methods (functions) that the objects created from the class will have.
Think of a class as a sketch of a house. It contains all the details about the floors, doors, and windows, but it isn't a house itself.
An Object is an instance of a class. When a class is defined, no memory is allocated until an object of that class is created.
If the class is the "sketch," the object is the actual house built using that sketch. You can build many houses (objects) from a single sketch (class).
Attributes: Variables that belong to a class (representing the "state" or "data").
Methods: Functions defined inside a class (representing the "behavior").
The self Parameter: A reference to the current instance of the class. It is used to access variables that belong to the class.
In this example, we create a Car blueprint and then create two specific car objects from it.
# Defining the Class class Car: # Class attribute (shared by all instances) category = "Automobile" # Constructor method (Initializing attributes) def __init__(self, brand, model): self.brand = brand # Instance attribute self.model = model # Instance attribute # Instance Method (Behavior) def display_info(self): print(f"This is a {self.brand} {self.model}.") # Creating Objects (Instances) car1 = Car("Toyota", "Corolla") car2 = Car("Tesla", "Model 3") # Accessing attributes and methods car1.display_info() # Output: This is a Toyota Corolla. car2.display_info() # Output: This is a Tesla Model 3.
The __init__ method is a special method called a Constructor. Python calls it automatically when you create a new object. Its primary purpose is to initialize the object's attributes with values.
| Concept | Analogy (The Architect) | Python Context |
| Class | The Blueprint / Drawing | class Student: |
| Object | The actual building | s1 = Student() |
| Attributes | Color, number of rooms, height | self.name, self.age |
| Methods | Open door, turn on lights | def study(self): |
Organization: Groups related data and functions together.
Reusability: Once a class is defined, you can create thousands of objects without rewriting code.
Inheritance: You can create a new class (e.g., ElectricCar) based on an existing class (Car), saving time.
Copyright ©2025. All Rights Reserved Emblab THE RAVE INNOVATION