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 |
|---|
| Python OOPS – Introduction |
| Python Classes and Objects |
| Python Object Methods |
| Python Inheritance |
| Polymorphism in Python |
| Python Access Modifiers |
| Exercises & Assignments |
|---|
| No Content Found. |
| Interview Questions & Answers |
|---|
| What is the use of self in Python? |
| What are public, protected and private attributes in Python? |
| What is the __init__() method in Python? |
| What is inheritance in Python? |