__init__ Method (Constructor)Introduction π
The __init__ method is one of the most important parts of Pythonβs OOP system. It is called **automatically** whenever a new object (instance) of a class is created. This method is known as the **constructor** because it βconstructsβ the object by initializing its attributes.
Note
__init__ as the setup function for every object β it prepares the object with initial values.1. Basic Structure of __init__ π§±
basic_init.py
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
p = Person("Sathish", 23)
print(p.name, p.age)β self refers to the current object
β Arguments passed to the class are received by __init__
β Attributes are created using self.attribute
2. Why Use __init__? π€
- β To set initial values for attributes
- β To perform required setup for each object
- β To enforce required parameters when creating objects
- β To create instance attributes
3. Default Values in __init__ β¨
default_values.py
class User:
def __init__(self, name, country="India"):
self.name = name
self.country = country
u1 = User("Arun")
u2 = User("John", "USA")
print(u1.country)
print(u2.country)β Useful when some attributes should have predefined values.
4. Creating Objects Without Attributes π§©
empty_init.py
class Demo:
def __init__(self):
print("Object created!")
d = Demo()5. Validating Data Inside __init__ π‘οΈ
validation_init.py
class BankAccount:
def __init__(self, balance):
if balance < 0:
raise ValueError("Balance cannot be negative")
self.balance = balance
a = BankAccount(500)
print(a.balance)Note
6. Using __init__ to Create Complex Attributes π§
complex_attributes.py
class Student:
def __init__(self, name, marks):
self.name = name
self.marks = marks
self.average = sum(marks) / len(marks)
s = Student("Sathish", [90, 85, 95])
print(s.average)β Pre-calculating values inside the constructor.
7. Calling Other Methods Inside __init__ π
call_method_init.py
class Player:
def __init__(self, name):
self.name = name
self.intro()
def intro(self):
print(f"Welcome, {self.name}!")
p = Player("Arun")β Constructor can trigger setup actions.
8. __init__ vs Class Methods vs Static Methods βοΈ
| Method Type | First Parameter | Used For |
|---|---|---|
| Instance Method | self | Object behaviors |
| Class Method | cls | Class-level operations, alternative constructors |
| Static Method | None | Utility functions |
| __init__ (Constructor) | self | Initializing object attributes |
9. Multiple Constructors? Use Class Methods! ποΈ
alt_constructor.py
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
@classmethod
def from_birth_year(cls, name, birth_year):
return cls(name, 2025 - birth_year)
p = Person.from_birth_year("Sathish", 2000)
print(p.name, p.age)Note
10. Real-World Example: Product Class ποΈ
product_example.py
class Product:
def __init__(self, name, price, discount=0):
self.name = name
self.price = price
self.discount = discount
def final_price(self):
return self.price - (self.price * self.discount / 100)
p = Product("Laptop", 50000, 10)
print(p.final_price())11. Real-World Example: User Registration System π
user_registration.py
class User:
def __init__(self, username, password):
self.username = username
self.password = password
def check_login(self, user, pwd):
return self.username == user and self.password == pwd
u = User("admin", "1234")
print(u.check_login("admin", "1234"))12. Best Practices π‘
- β Keep
__init__lean β avoid heavy logic - β Use it only for initializing instance attributes
- β Validate data when necessary
- β Always include
selfas the first argument - β Use default parameters when possible
Conclusion π
__init__ method breathes life into your objects β it defines their identity and initial state.β β¨You now fully understand the __init__ Method in Python! Want the next topic? Try Magic Methods, Encapsulation, Inheritance, or Polymorphism. Just tell me! π