What is the __init__() method in Python?
__init__() is a special method of a class that runs automatically when a new object is created. It is used to set the starting values of the object, so it works like a constructor in other languages.
class Car:
def __init__(self, brand, year):
self.brand = brand
self.year = year
car = Car("Tata", 2024)
print(car.brand)
print(car.year)
Output:
Tutorials Class - Output Window
Tata
2024
The first parameter is always self. The other values come from the call Car("Tata", 2024). Technically the object is created by __new__() first and then __init__() sets it up, but you rarely write __new__() yourself. See Python Classes and Objects.
Learn more about the similar topics:
| Tutorials |
|---|
| No Content Found. |
| Exercises & Assignments |
|---|
| No Content Found. |
| Interview Questions & Answers |
|---|
| No Content Found. |