Python

Python Basics

Data Structures in Python

Control Flow and Loops

Functions and Scope

Object-Oriented Programming (OOP)

Python Programs


📘 Classes and Objects (class) in Python

Python is widely known for its clean syntax and ease of learning. One of its most powerful features is Object-Oriented Programming (OOP), where classes and objects play a central role. If you’re new to Python or programming in general, understanding how to use classes and objects will level up your ability to write organized, modular, and reusable code.

In this article, we’ll explore what classes and objects are, how to create and use them in Python, and how they help you build real-world applications.


🧠 Why Learn Classes and Objects?

Real-world systems are made of entities that interact—think of cars, employees, or students. Each of these can be modeled in code using objects, and the blueprint for those objects is defined using classes.

Here’s why it matters:

  • 🔄 Reusability: Classes let you create multiple instances without rewriting code.
  • 📦 Encapsulation: Bundles data and behavior together.
  • ⚙️ Maintainability: Easier to debug, update, and scale.
  • 🌍 Real-world modeling: Makes code intuitive by mimicking real-world structures.

📌 Prerequisites

To follow this guide, you should be familiar with:

  • Python variables and data types
  • Functions and loops
  • Basic understanding of programming logic

🔍 What is a Class?

A class is a blueprint for creating objects. It defines how an object should behave and what data it should hold.

Here’s how you define a class in Python:

class Car:
pass

This Car class doesn’t do anything yet. Let’s make it more useful.


🧱 What is an Object?

An object is an instance of a class. When you create an object, Python allocates memory for it and links it to the class structure.

my_car = Car()

Now my_car is an object of the Car class.


🔧 Using the __init__() Method

The __init__() method is a constructor. It runs automatically when a new object is created and is used to initialize values.

class Car:
def __init__(self, brand, model):
self.brand = brand
self.model = model

Now when we create a car object:

car1 = Car("Toyota", "Corolla")
print(car1.brand) # Output: Toyota

🧠 Understanding self

The self parameter refers to the current object. It allows you to access variables and methods of the class in its body.

class Student:
def __init__(self, name):
self.name = name
def greet(self):
return f"Hello, my name is {self.name}"

Create and use the object:

student1 = Student("Alice")
print(student1.greet()) # Output: Hello, my name is Alice

🔨 Adding Methods to a Class

A class can contain functions, called methods, that define the behavior of objects.

class Calculator:
def __init__(self, number):
self.number = number
def square(self):
return self.number ** 2

Usage:

calc = Calculator(4)
print(calc.square()) # Output: 16

🔄 Class Variables vs Instance Variables

  • Instance variables are specific to each object.
  • Class variables are shared across all instances.
class Dog:
species = "Canine" # Class variable
def __init__(self, name):
self.name = name # Instance variable
dog1 = Dog("Max")
dog2 = Dog("Rocky")
print(dog1.species) # Output: Canine
print(dog1.name) # Output: Max

📘 Real-Life Example: Employee Class

class Employee:
company = "TechCorp" # class variable
def __init__(self, name, role):
self.name = name
self.role = role
def info(self):
return f"{self.name} works as a {self.role} at {self.company}"
emp1 = Employee("John", "Developer")
emp2 = Employee("Sara", "Designer")
print(emp1.info()) # Output: John works as a Developer at TechCorp
print(emp2.info()) # Output: Sara works as a Designer at TechCorp

🧪 Mini Examples to Practice

  1. Book Class
class Book:
def __init__(self, title, author):
self.title = title
self.author = author
  1. Bank Account Class
class BankAccount:
def __init__(self, balance=0):
self.balance = balance
def deposit(self, amount):
self.balance += amount
return self.balance
  1. Shape Class with Area Calculation
class Rectangle:
def __init__(self, width, height):
self.width = width
self.height = height
def area(self):
return self.width * self.height

✅ Best Practices

  • Use clear and descriptive class names.
  • Keep methods short and focused.
  • Document classes with docstrings.
  • Use underscores (_) for private variables by convention.
  • Follow PEP8 styling for consistency.

🧩 Summary

Let’s recap the key points:

  • A class is a blueprint, and an object is an instance of that blueprint.
  • The __init__() method initializes the object with data.
  • self allows access to object-specific attributes and methods.
  • Classes help organize code and make it modular and reusable.
  • OOP is essential for building real-world Python applications.

Learning classes and objects is your first step toward mastering object-oriented programming in Python. From games to web apps, they form the building blocks of well-structured Python code.


Previous > Object-Oriented Programming        Next > The __init__() Constructor