- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How does constructor method __init__ work in Python?
__init__
"__init__" is a reserved method in python classes. It is known as a constructor in OOP concepts. This method called when an object is created from the class and it allows the class to initialize the attributes of a class.
How can we use "__init__ " ?
Let's consider that we are creating a class named Car. Car can have attributes like "color", "model", "speed" etc. and methods like "start", "accelarate", "change_ gear" and so on.
Example
class Car(object): def __init__(self, model, color, speed): self.color = color self.speed = speed self.model = model def start(self): print("started") def accelerate(self): print("accelerating...") def change_gear(self, gear_type): print("gear changed")
So we have used the constructor __init__ method to initialize the class attributes.
Advertisements