When you start learning classes in Python, the __init__
method might look confusing. It has double underscores, it shows up automatically, and you never really “call” it yourself.
But once you understand it, it becomes one of the most powerful and useful tools in Python’s object-oriented programming.
🧠 What is __init__
?
__init__()
is a special method in Python classes. It’s also known as the constructor.
Whenever you create a new object from a class, Python automatically runs the __init__
method.
It’s used to initialize the object’s data (i.e., set its default values or receive initial input).
🔍 Syntax
class Student:
def __init__(self, name, age):
self.name = name
self.age = age
When you create a new Student
object:
s1 = Student("Ali", 20)
Python automatically runs:
Student.__init__(s1, "Ali", 20)
🧠 You don’t call
__init__()
Python does that for you when you create an object.
✅ Why Use __init__
?
- To give each object its own unique data
- To ensure important attributes exist as soon as the object is created
- To make your class useful right from the start
✍️ Real Example: Student Class
class Student:
def __init__(self, name, grade):
self.name = name
self.grade = grade
def info(self):
print(f"{self.name} is in Grade {self.grade}")
s1 = Student("Fatima", 10)
s2 = Student("Ali", 8)
s1.info() # Fatima is in Grade 10
s2.info() # Ali is in Grade 8
🔁 What if You Don’t Use __init__
?
Your object won’t have any data unless you assign it manually later:
class Empty:
pass
obj = Empty()
obj.name = "Noor"
print(obj.name) # Works, but messy
✅ __init__
makes sure every object is built properly from the beginning.
💡 Quick Analogy
Think of
__init__()
like a form you fill out when creating a new account.
You provide your name, email, and password at signup that’s what__init__
does behind the scenes.
✅ Best Practices
Tip | Why it matters |
---|---|
Always include self | Refers to the object being created |
Initialize key attributes | Keeps your objects structured and predictable |
Avoid hardcoding inside __init__ | Makes class reusable with different inputs |
⚠️ Common Beginner Mistakes
❌ Mistake 1: Forgetting self
def __init__(name): # ❌
✅ Fix:
def __init__(self, name):
❌ Mistake 2: Using different attribute names
self.nam = name # Then you try to use self.name later
✅ Be consistent!