Python
Python Basics
- Introduction to Python and Its History
- Python Syntax and Indentation
- Python Variables and Data Types
- Dynamic and Strong Typing
- Comments and Docstrings
- Taking User Input (input())
- Printing Output (print())
- Python Operators (Arithmetic, Logical, Comparison)
- Type Conversion and Casting
- Escape Characters and Raw Strings
Data Structures in Python
- Lists
- Dictionaries
- Dictionary Comprehensions
- Strings and String Manipulation
- Tuples
- Python Sets: Unordered Collections
- List Comprehensions and Generator Expressions
- Set Comprehensions
- String Formatting
- Indexing and Slicing
Control Flow and Loops
- Conditional Statements: if, elif, and else
- Loops and Iteration
- While Loops
- Nested Loops
- Loop Control Statements
- Iterators and Iterables
- List, Dictionary, and Set Iterations
Functions and Scope
- Defining and Calling Functions (`def`)
- Function Arguments (`*args`, `**kwargs`)
- Default Arguments and Keyword Arguments
- Lambda Functions
- Global and Local Scope
- Function Return Values
- Recursion in Python
Object-Oriented Programming (OOP)
- Object-Oriented Programming
- Classes and Objects
- the `__init__()` Constructor
- Instance Variables and Methods
- Class Variables and `@classmethod`
- Encapsulation and Data Hiding
- Inheritance and Subclasses
- Method Overriding and super()
- Polymorphism
- Magic Methods and Operator Overloading
- Static Methods
- Abstract Classes and Interfaces
Python Programs
- Array : Find median in an integer array
- Array : Find middle element in an integer array
- Array : Find out the duplicate in an array
- Array : Find print all subsets in an integer array
- Program : Array : Finding missing number between from 1 to n
- Array : Gap and Island problem
- Python Program stock max profit
- Reverse words in Python
- Python array duplicate program
- Coin change problem in python
- Python Write fibonacci series program
- Array : find all the pairs whose sum is equal to a given number
- Find smallest and largest number in array
- Iterate collections
- List comprehensions
- Program: Calculate Pi in Python
- String Formatting in Python
📘 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: Canineprint(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 TechCorpprint(emp2.info()) # Output: Sara works as a Designer at TechCorp
🧪 Mini Examples to Practice
- Book Class
class Book: def __init__(self, title, author): self.title = title self.author = author
- Bank Account Class
class BankAccount: def __init__(self, balance=0): self.balance = balance
def deposit(self, amount): self.balance += amount return self.balance
- 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