0
0
PythonConceptBeginner · 3 min read

What is __init__ Method in Python: Explanation and Example

In Python, the __init__ method is a special function called a constructor that runs automatically when you create a new object from a class. It is used to set up the initial state of the object by assigning values to its attributes.
⚙️

How It Works

The __init__ method is like the setup step when you buy a new gadget. Imagine you get a new phone and you immediately set your preferences like language, wallpaper, and ringtone. Similarly, when you create a new object from a class, Python calls the __init__ method to set up the object with initial values.

This method is automatically called right after the object is created, so you don't have to call it yourself. It usually takes the object itself as the first parameter (named self) and other parameters to customize the object’s attributes.

💻

Example

This example shows a simple class Car with an __init__ method that sets the car's brand and year when a new car object is created.

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

    def display_info(self):
        print(f"Car brand: {self.brand}, Year: {self.year}")

my_car = Car("Toyota", 2020)
my_car.display_info()
Output
Car brand: Toyota, Year: 2020
🎯

When to Use

Use the __init__ method whenever you want to create objects that start with specific information. For example, if you are making a program to manage a library, you can use __init__ to set the title, author, and year of each book when you add it.

This helps keep your code organized and makes sure every object has the data it needs right from the start.

Key Points

  • __init__ is called automatically when creating an object.
  • It initializes the object's attributes with values.
  • The first parameter is always self, which refers to the object itself.
  • You can pass extra parameters to customize each object.
  • It helps set up objects cleanly and clearly.

Key Takeaways

The __init__ method sets up new objects with initial values automatically.
It is called right after an object is created from a class.
Use __init__ to give each object its own unique data.
The first parameter of __init__ is always self, representing the object.
It keeps your code organized by initializing attributes clearly.