Python __init__() Method

🐍 Python __init__() Method

The __init__() method in Python is a constructor method.
It automatically runs every time an object is created from a class.


🔍 Why __init__()?

  • It initializes the object’s attributes.

  • Helps set default or custom values when creating objects.


🧠 Basic Syntax



 


✅ Example 1: Simple __init__() Usage


 

✔ The arguments "John" and 20 are passed to __init__().


🧠 Understanding self

  • self refers to the current object.

  • It must be the first parameter in every method (not just __init__).


Example with Method


 


🎯 Default Values in __init__()


 


🧩 Multiple Objects with __init__()


 


🔥 __init__() Can Execute Logic


 

Output:

Bank account created!

⚙ Without __init__() vs With

❌ Without

class Person:
pass
p = Person()

✔ Works, but no data assignment.


✔ With


 


📌 Optional Parameters


 


✨ Summary Table

Feature Description
Type Constructor method
Auto Execute Yes, when creating object
First Parameter Always self
Purpose Initialize object attributes

You may also like...