__init__() method is a constructor which is automatically called 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.
__init__() with Parameters
You can pass parameters to initialize multiple attributes.
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
a = Person("Max", 30)
b = Person("Emilia", 25)
print(a.name, a.age)
print(b.name, b.age)
Output
Max 30 Emilia 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.
Default Parameters in __init__()
Like regular functions, __init__() can have parameters with default values.
class Dog:
def __init__(self, name, breed="Mixed", age=1):
self.name = name
self.breed = breed
self.age = age
a = Dog("Buddy")
b = Dog("Max", "Golden Retriever", 5)
print(a.name, a.breed, a.age)
print(b.name, b.breed, b.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.
__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 first calls B.__init__(). Inside B.__init__, the line super().__init__() calls the parent’s (A) constructor.
- As a result, "A init called" is printed first.
- After the parent class initialization completes, remaining code in B.__init__() executes and "B init called" is printed.