What is __init__ in Python? Understand Constructors the Right Way

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

Python
class Student:
    def __init__(self, name, age):
        self.name = name
        self.age = age

When you create a new Student object:

Python
s1 = Student("Ali", 20)

Python automatically runs:

Python
Student.__init__(s1, "Ali", 20)

🧠 You don’t call __init__() Python does that for you when you create an object.


✅ Why Use __init__?

  1. To give each object its own unique data
  2. To ensure important attributes exist as soon as the object is created
  3. To make your class useful right from the start

✍️ Real Example: Student Class

Python
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}")

Python
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:

Python
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

TipWhy it matters
Always include selfRefers to the object being created
Initialize key attributesKeeps your objects structured and predictable
Avoid hardcoding inside __init__Makes class reusable with different inputs

⚠️ Common Beginner Mistakes

❌ Mistake 1: Forgetting self

Python
def __init__(name):   # ❌

✅ Fix:

Python
def __init__(self, name):

❌ Mistake 2: Using different attribute names

Python
self.nam = name  # Then you try to use self.name later

✅ Be consistent!


💌 Stay Updated with PyUniverse

Want Python and AI explained simply straight to your inbox?

Join hundreds of curious learners who get:

  • ✅ Practical Python tips & mini tutorials
  • ✅ New blog posts before anyone else
  • ✅ Downloadable cheat sheets & quick guides
  • ✅ Behind-the-scenes updates from PyUniverse

No spam. No noise. Just useful stuff that helps you grow one email at a time.

🛡️ I respect your privacy. You can unsubscribe anytime.

Leave a Comment