Nearby lessons

101 of 159

Python - __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.

🐍Code Cell
1class Student:
2 def __init__(self, name, rollno, marks):
3 self.name = name
4 self.rollno = rollno
5 self.marks = marks
6 
7 
8s1 = Student("Durga", 101, 80)
9s2 = Student("Sunny", 102, 100)
10 
11print(s1.name, s1.marks)
12print(s2.name, s2.marks)
Output
Durga 80
Sunny 100

Important Points

  • self must 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
selfCurrent object reference
Instance variablesInitialized 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 Questions
Progress: 0 / 6