__init__ in Python
__init__ method in Python is a constructor. It runs automatically when a new object of a class is created. Its main purpose is to initialize the object’s attributes and set up its initial state. When an object is created, memory is allocated for it, and __init__ helps organize that memory by assigning values to attributes.
Let’s look at some examples.
1. __init__ with Parameters
You can pass multiple parameters to set up different attributes.
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
p1 = Person("Alice", 30)
p2 = Person("Bob", 25)
print(p1.name, p1.age) # Alice 30
print(p2.name, p2.age) # Bob 25
Output
Alice 30 Bob 25
Explanation:
- self: refers to the current object (always the first parameter).
- name and age: parameters passed when creating the object.
- self.name and self.age: object attributes that store these values.
2. Default Parameters in __init__
Like normal functions, you can use default values in constructors.
class Dog:
def __init__(self, name, breed="Mixed", age=1):
self.name = name
self.breed = breed
self.age = age
d1 = Dog("Buddy")
d2 = Dog("Max", "Golden Retriever", 5)
print(d1.name, d1.breed, d1.age)
print(d2.name, d2.breed, d2.age)
Output
Buddy Mixed 1 Max Golden Retriever 5
Explanation:
- breed="Mixed" and age=1 are default values.
- When creating Dog("Buddy"), Python uses the defaults → breed = "Mixed", age = 1.
- When creating Dog ("Max", "Golden Retriever", 5), the defaults are overwritten by the provided values.
3.__init__ Method with Inheritance
When using inheritance, both parent and child classes can have __init__ methods.
class A:
def __init__(self):
print("A init called")
class B(A):
def __init__(self):
super().__init__() # Call parent __init__
print("B init called")
obj = B()
Output
A init called B init called
Explanation:
- When obj = B () is created, Python looks for B.__init__.
- Inside B.__init__, the line super().__init__() calls the parent’s (A) constructor.
- So "A init called" is printed first.
- Then the rest of B.__init__ runs, printing "B init called".