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
Mastering the __init__()
Constructor in Python
In Python, when you create a class and want to initialize its attributes automatically when an object is created, you use a special method called the __init__()
constructor. Understanding this method is key to writing clean, reusable, and efficient object-oriented Python code. This guide will walk you through what __init__()
is, why it matters, and how to use it with clear examples.
🔹 What Is the __init__()
Method?
In Python, __init__()
is a special method that gets called automatically when you create an instance (object) of a class. It’s part of a class’s lifecycle and is commonly referred to as a constructor.
Think of __init__()
as the method that “builds” your object. It allows you to set up the object with default or user-specified values when it’s first created.
🔸 Basic Syntax:
class MyClass: def __init__(self, arg1, arg2): self.arg1 = arg1 self.arg2 = arg2
🔹 Why Is __init__()
Important?
- It automates object initialization, reducing repetitive code.
- Allows custom parameters for different instances.
- Ensures data integrity by requiring key attributes at object creation.
- Enhances code readability and scalability.
Without __init__()
, every time you create an object, you would need to manually assign values, which can lead to inconsistency or bugs.
🔹 Prerequisites to Understand __init__()
Before diving deep, you should be comfortable with:
- Python basics: variables, functions
- Defining and using classes
- Using
self
to access class attributes
🔹 What Will This Guide Cover?
- Purpose and behavior of
__init__()
- How it differs from other methods
- Common use cases
- Mistakes to avoid
- 5 practical examples
🔹 Must-Know Concepts Before Using __init__()
1. The self
Parameter
self
refers to the current instance of the class. It’s how Python allows each object to hold its own data.
2. Method Overloading
In Python, you can’t overload constructors like in Java or C++. Instead, you handle optional parameters using default values.
3. Multiple Constructors?
Python doesn’t support multiple __init__()
methods per class. But you can work around this by using conditional logic inside a single __init__()
.
🔹 5 Real-World Examples of Using __init__()
đź§ľ Example 1: Simple Object Initialization
class Person: def __init__(self, name, age): self.name = name self.age = age
p1 = Person("Alice", 25)print(p1.name) # Output: Aliceprint(p1.age) # Output: 25
Use Case: Automatically store details of a person when the object is created.
đź§ľ Example 2: Default Values in Constructor
class Car: def __init__(self, brand="Toyota", color="Black"): self.brand = brand self.color = color
c1 = Car()print(c1.brand) # Output: Toyota
c2 = Car("Honda", "Red")print(c2.brand) # Output: Honda
Use Case: Flexible object creation—use default or custom data.
đź§ľ Example 3: Using __init__()
in Class Hierarchy
class Animal: def __init__(self, species): self.species = species
class Dog(Animal): def __init__(self, breed): super().__init__("Dog") self.breed = breed
d = Dog("Labrador")print(d.species) # Output: Dogprint(d.breed) # Output: Labrador
Use Case: Proper initialization of parent and child classes.
đź§ľ Example 4: Validating Input During Initialization
class Product: def __init__(self, name, price): if price < 0: raise ValueError("Price cannot be negative.") self.name = name self.price = price
Use Case: Ensure that only valid values are accepted when creating an object.
đź§ľ Example 5: Counting Created Objects
class Counter: count = 0
def __init__(self): Counter.count += 1
a = Counter()b = Counter()print(Counter.count) # Output: 2
Use Case: Tracking how many times a class has been instantiated.
🔹 Common Mistakes to Avoid
-
Forgetting
self
- Wrong:
def __init__(name)
- Correct:
def __init__(self, name)
- Wrong:
-
Trying to overload
__init__()
Python only allows one__init__()
method per class. Use optional parameters instead. -
Assigning variables without
self.
If you writename = name
inside__init__()
, it won’t store the value in the object. Useself.name = name
.
🔹 Best Practices
- Keep
__init__()
clean and readable. - Avoid complex logic inside constructors.
- Validate parameters if necessary.
- Use docstrings to explain purpose and parameters.
🔹 Final Thoughts
The __init__()
method is more than just a constructor—it’s your first line of defense for clean, reliable, and maintainable Python code. It helps define what your object is and what data it holds right at the start.
Whether you’re building simple classes or large applications, knowing how to properly use __init__()
will help you write better, clearer, and more Pythonic code.
Previous > Classes and Objects        Next > Instance Variables and Methods