PythonOOPs Concepts
Init Method
Understanding init method
__init__is a special method in Python. It is automatically called when a new object of a class is created.- Its main purpose is to initialize instance variables for the object.

Why __init__ is Needed?
- To assign initial values to object attributes
- To allow dynamic configuration of objects
- To ensure each object can have its own unique data
Without __init__, attributes must be added manually after object creation.

Understanding self
selfrefers to the current object- It allows access to:
- Instance variables
- Other methods of the same object
- Variables created using
selfbecome object attributes
self.cpu = cpuThis creates an instance variable, not a local variable.

Example: __init__ Without Parameters
class Computer:
def __init__(self):
print("init called")
self.cpu = "i5"
def config(self):
print("i7", "16GB", "1TB")
com1 = Computer()
com2 = Computer()
print(com1.cpu)
com1.config()Output:
init called
init called
i5
i7 16GB 1TBExplanation:
__init__runs once per objectcpuis an instance variable- Both objects get their own
cpuvalue
Example: __init__ With Parameters
The init method enables per-object customization, allowing each object of a class to maintain its own configuration and data.
- Each object stores unique values in its instance variables
- Instance variables hold object-specific data
- Different objects of the same class can behave differently based on initialization values
class Computer:
def __init__(self, cpu, ram, ssd):
print("init called")
self.cpu = cpu
self.ram = ram
self.ssd = ssd
def config(self):
print(self.cpu, self.ram, self.ssd)
com1 = Computer("i5", "16GB", "512GB")
com2 = Computer("i9", "96GB", "2TB")
print(com1.cpu)
com1.config()
com2.config()Output:
init called
init called
i5 16GB 512GB
i9 96GB 2TBEach object (com1, com2) has its own independent configuration, even though they belong to the same class.
Dynamic Attribute Creation
Python allows attributes to be added to objects at runtime, even if they are not predefined in the class.
Example:
obj.webcam = "External"This highlights Python’s dynamic language nature, where objects can be extended after creation.
Real-World Analogy
-
Buying a laptop:
- Some laptops come with a webcam
- Some require an external webcam
-
Similarly, Python objects can have different attributes depending on how they are initialized
Summary
__init__initializes objects after creation and is not a constructor.selfrefers to the current object and is used to define instance variables.- Instance variables are object-specific, while class variables are shared.
__init__enables dynamic, flexible, and maintainable object creation in Python.
Written By: Muskan Garg
How is this guide?
Last updated on
