Special Methods in Python: __init__ and __str__
Python has special methods called dunder methods (double underscore), like __init__ and __str__.
These methods control object behavior.
__init__ Method - The Constructor
- What it does: Initializes an object's attributes when it is created.
- When it runs: Automatically called when you create an object using the class.
Example:
class Student:
def __init__(self, name, age):
self.name = name
self.age = age
s1 = Student("Amit", 15)
print(s1.name) # Output: Amit
print(s1.age) # Output: 15
Notes:
- __init__ is optional but commonly used.
- The first parameter is always self (refers to the current object).
__str__ Method - String Representation
- What it does: Returns a readable string when you print an object.
- When it runs: Automatically called when using print() or str() on the object.
Example:
class Student:
def __init__(self, name, age):
self.name = name
self.age = age
def __str__(self):
return f"Student Name: {self.name}, Age: {self.age}"
s1 = Student("Amit", 15)
print(s1) # Output: Student Name: Amit, Age: 15
Notes:
- Without __str__, print shows a memory address.
- Helps make object output user-friendly.
Quick Comparison Table:
| Method | Purpose | When It's Called |
|------------|--------------------------------------|--------------------------------|
| __init__ | Initializes object attributes | When an object is created |
| __str__ | Returns readable string of object | When print() or str() is used |