What Are Classes and Objects?
Now we will dive into Python OOP concepts, so learn this carefully to make your journey in Object-Oriented Programming more effective.
- Class: A class is a blueprint or template in our program. it defines what attributes (data) and methods (actions/functions) an object will have. You can consider it as a plan for building something.
- Object: An object is a real instance that is created from that blueprint. Now, the object contains actual values for the attributes and can perform the class methods.
Real-Life Example:
Imagine a class as a blueprint of a car, and it shows the design, features, and functionalities. An object is the actual car you drive, with a unique color, engine type, and mileage.
Why Use Classes and Objects in Python?
- Classes allow you to group related data (attributes) and actions (methods).
- Once you create a class, you can create multiple objects from it. For example, A car class can create many car objects with different colors, models, or engine types without rewriting code.
- Classes allow you to hide internal details and expose only what’s necessary. For example, a BankAccount class hides the balance calculation details but provides simple methods like deposit() or withdraw().
- Programs with classes are easy to update or debug because all the functionality is grouped.
Python Class Syntax
1) First, we define a class:
class ClassName:
# Attributes (data) and methods (functions) go here
- The class keyword tells Python you are creating a class.
- ClassName is the name of your class (use meaningful names like Car or Student).
- We will define variables and functions inside the class.
2) Creating an Object:
object_name = ClassName()
- This line creates an instance (object) of your class.
- Each object can have its own separate data stored in attributes.
Examples of Class and Objects
1) We creates a bakery Item Class with Object:
class BakeryItem:
def __init__(self, name, price, quantity):
self.name = name
self.price = price
self.quantity = quantity
def total_cost(self):
return self.price * self.quantity
def description(self):
return f"{self.quantity} {self.name}(s) cost ₹{self.total_cost()}"
# Creating objects
cake = BakeryItem("Cake", 150, 2)
bread = BakeryItem("Bread", 40, 5)
print(cake.description())
print(bread.description())
Final output of this code:
2 Cake(s) cost ₹300
5 Bread(s) cost ₹200
Let’s understand with steps:
Step 1: cake.description()
- cake.price = 150, cake.quantity = 2
- cake.total_cost() = 150 * 2 = 300
- cake.description() → “2 Cake(s) cost ₹300”
Step 2: bread.description()
- bread.price = 40, bread.quantity = 5
- bread.total_cost() = 40 * 5 = 200
- bread.description() → “5 Bread(s) cost ₹200”
2) Mobile Phone Battery Simulator
class MobilePhone:
def __init__(self, brand, battery=100):
self.brand = brand
self.battery = battery
def use_phone(self, hours):
self.battery -= hours * 10
if self.battery < 0:
self.battery = 0
return f"{self.brand} battery is now {self.battery}%"
def charge(self):
self.battery = 100
return f"{self.brand} is fully charged!"
# Creating objects
phone1 = MobilePhone("Samsung")
phone2 = MobilePhone("iPhone", 50)
print(phone1.use_phone(3)) # Outputs: Samsung battery is now 70%
print(phone2.charge()) # Outputs: iPhone is fully charged!
Code Output:
Samsung battery is now 70%
iPhone is fully charged!
Try to understand this code logic by yourself and practice continuously.
Key Concepts of Classes and Objects In Python
- Attributes: Attributes are like the details or properties of an object, and describe the current state of that object. For example, if you have a car, so attributes will be color, model or speed.
- Methods: Methods define what an object can do. They are basically functions inside a class that can interact with the object’s attributes.
- Constructor (__init__): The constructor is a special method that runs automatically when a new object is created. Without a constructor, you would have to manually set attributes after creating each object.
- What Are Modules In Python?
- What Is a Function In Python?
- What Is Python String Formatting?
- What Is a Python List?
- How Can We Use Lambda Function?
What Is Instance and Class Variables In Python?
Python classes have two main type of variables to store data: instance variables and class variables.
1) Instance Variables
- These variables are unique to each object.
- Defined inside the constructor (__init__) using self.
- Each object can have different values for the same instance variable.
What is an instance in Python?
An instance is a real and usable version of a class. A class is just a design or blueprint, but an instance is the actual object created from that design.
Example of Instance Variable
SmartPlant – Tracking Plant Growth: Here we create a Plant class where each plant object has its own instance variables like height and water_level.
class SmartPlant:
garden_name = "Happy Garden" # Class variable (same for all plants)
def __init__(self, plant_name, height_cm):
self.plant_name = plant_name # Instance variable
self.height_cm = height_cm # Instance variable
self.water_level = 0 # Instance variable (starts empty)
# Creating objects
plant1 = SmartPlant("Rose", 12)
plant2 = SmartPlant("Tulip", 9)
# Updating instance variables
plant1.water_level += 3
plant2.water_level += 1
print(plant1.plant_name, "-> Height:", plant1.height_cm, "cm | Water:", plant1.water_level, "|", plant1.garden_name)
print(plant2.plant_name, "-> Height:", plant2.height_cm, "cm | Water:", plant2.water_level, "|", plant2.garden_name)
Output will this:
Rose -> Height: 12 cm | Water: 3 | Happy Garden
Tulip -> Height: 9 cm | Water: 1 | Happy Garden
- Here you can see, every object stores its own data, which is the main purpose of instance variables.
2) Class Variables
- A class variable is a variable that is shared by all objects of a class.
- It is created inside the class, but outside any method.
- Every object can access it.
- Your one change in a class can reflect on all objects.
Example of Class Variables
Creating a planet explorer app:
class Planet:
galaxy = "Milky Way" # Class variable (same for every planet)
def __init__(self, name, distance_from_sun):
self.name = name # Instance variable
self.distance_from_sun = distance_from_sun # Instance variable
# Creating planet objects
planet1 = Planet("Mercury", "57 million km")
planet2 = Planet("Neptune", "4.5 billion km")
print(planet1.name, "is", planet1.distance_from_sun, "away in the", planet1.galaxy)
print(planet2.name, "is", planet2.distance_from_sun, "away in the", planet2.galaxy)
Output:
Mercury is 57 million km away in the Milky Way
Neptune is 4.5 billion km away in the Milky Way
Here, the galaxy stays constant for all planets because it’s a class variable. But name and distance_from_sun differ for each object, so it refers to an instance variable.
Object Methods in Python
An object provides multiple methods to perform different tasks. You can consider it in three steps:
- A class is the design of a robot.
- An object is the real robot created from that design.
- A method is something the robot can walk, talk, or lift.
Example of Object Methods
Let’s create a simple code program to check the remaining water in a water bottle.
class WaterBottle:
def __init__(self, capacity, filled):
self.capacity = capacity # total bottle size
self.filled = filled # current water level
def drink(self, amount):
if amount > self.filled:
return "Not enough water left!"
self.filled -= amount
return f"Remaining water: {self.filled} ml"
# Creating an object
bottle = WaterBottle(1000, 600)
print(bottle.drink(200)) # Drink 200 ml
print(bottle.drink(500)) # Try drinking more than remaining
Final output:
Remaining water: 400 ml
Not enough water left!
Learn Further OOPs Concepts:

M.Sc. (Information Technology). I explain AI, AGI, Programming and future technologies in simple language. Founder of BoxOfLearn.com.