Nearby lessons
101 of 159Python - __init__ Method
📌 What You Will Learn
- Understand what the __init__ method is
- Know that self must be its first parameter
- Initialize instance variables with __init__
- Explain why only the last __init__ definition is used
- Use default arguments with __init__ for flexible object creation
What Is __init__?
__init__ is the constructor method in Python classes.
It runs automatically when an object is created.
Purpose
Its main purpose is to initialize instance variables.
When an object is created, the code inside __init__ executes immediately and sets up the initial state of that object.
Example
Each object created from the Student class gets its own name, rollno, and marks values.
Important Points
selfmust be the first parameter.- The method name must be
__init__. - It is optional, but very commonly used.
- If multiple
__init__methods are defined, only the last one remains available.
Summary
| Term | Meaning |
|---|---|
| __init__ | Constructor method |
| self | Current object reference |
| Instance variables | Initialized in constructor |
📝 Key Takeaways
- __init__ is the constructor method in Python classes
- It runs automatically when an object is created
- Its main purpose is to declare and initialize instance variables
- self must be the first parameter of __init__
- If multiple __init__ methods are defined, only the last one is used
🧠 Test Your Knowledge
6 QuestionsProgress: 0 / 6