0% found this document useful (0 votes)
3 views

Python

__init__() is a special method in Python that automatically initializes an object’s attributes when a class object is created. It enhances code readability, saves time by avoiding manual value assignments, and supports object-oriented programming principles. The method uses 'self' to refer to the current object and allows for the creation of multiple instances with unique attributes.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Python

__init__() is a special method in Python that automatically initializes an object’s attributes when a class object is created. It enhances code readability, saves time by avoiding manual value assignments, and supports object-oriented programming principles. The method uses 'self' to refer to the current object and allows for the creation of multiple instances with unique attributes.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 2

The __init__() method in Python is a special method that runs automatically when an object

of a class is created. It is called the constructor because it is used to initialize (set up) the
object with some values.

Simple Explanation:

 When you create an object, Python automatically calls __init__().

 It helps to assign values to the object’s attributes at the time of creation.

 self is used to refer to the current object.

Example:

class Person:

def __init__(self, name, age):

self.name = name # Assigning value to the 'name' attribute

self.age = age # Assigning value to the 'age' attribute

def show_info(self):

print(f"My name is {self.name} and I am {self.age} years old.")

# Creating an object of the Person class

p1 = Person("Chhavi", 22)

p1.show_info() # Output: My name is Chhavi and I am 22 years old.

Why __init__() is Important:

1. Automatic Initialization:

o It runs automatically when an object is created, saving time and effort.

o Without __init__(), we would have to set values manually after creating an


object.

2. Defines Object Attributes:

o It helps define attributes (variables) specific to each object.

o Example: If you create multiple Person objects, each can have a different
name and age.
3. Improves Code Readability & Organization:

o Makes code cleaner by ensuring every object starts with valid data.

o Avoids writing extra lines of code to set values later.

4. Encapsulation & Object-Oriented Programming (OOP):

o Helps in implementing OOP concepts by binding data (attributes) with


objects.

You might also like