Skip to content

Module 11 · Object-Oriented Programming — topic 7 of 25

__init__()

The initialiser method in detail: its parameters, setting attributes from arguments, computed attributes, calling other methods during initialisation, and calling a parent's __init__.

Beginner 10 min read·Lesson 164 of 306 in Python Programming

Learning objectives

  • Write __init__ methods with required and optional parameters
  • Compute derived attributes during initialisation
  • Call a parent class's __init__ with super()

Definition

__init__ is a special method that Python calls automatically right after a new instance is created. It receives the new object as self plus the arguments given to the class call, and sets up the object's initial state.

Introduction

Whenever you write Student("Asha", 101), Python creates the object and immediately calls Student.__init__(new_object, "Asha", 101). Whatever __init__ stores on self becomes the object's starting state.

Why it matters

Almost every class you write will have an __init__. Writing it well — clear parameters, complete state, no surprises — sets up everything else.

Detailed explanation

The signature mirrors how the class is called: def __init__(self, name, roll, year=1) allows Student("Asha", 101) or Student("Asha", 101, year=2).

The common pattern is to copy parameters to attributes: self.name = name.

Derived attributes can be computed from parameters: self.initials = ''.join(p[0] for p in name.split()). If they must stay in sync with other attributes, use a property instead (see Properties).

__init__ may call other methods (self.reset()) to share setup code.

In a subclass, call super().__init__(...) to let the parent initialise its part before adding your own attributes.

Keep __init__ fast and free of heavy work such as network calls; do those in explicit methods.

Syntax

Python
class Student:
def __init__(self, name, roll, year=1):
self.name = name
self.roll = roll
self.year = year
self.marks = {} # empty container per object
class Topper(Student):
def __init__(self, name, roll, rank):
super().__init__(name, roll)
self.rank = rank
  • Called automatically after creation.
  • Set every attribute here.
  • Use super().__init__ in subclasses.

Code examples

Parameters become attributes

Python
class Student:
def __init__(self, name, roll, year=1):
self.name = name
self.roll = roll
self.year = year
self.initials = "".join(part[0] for part in name.split())
s = Student("Asha Rao", 101)
t = Student("Ravi Kumar", 102, year=3)
print(s.initials, s.year, t.initials, t.year)
Output
AR 1 RK 3

__init__ is called for you

Python
class Logger:
def __init__(self, name):
print(f"initialising {name}")
self.name = name
self.lines = []
app = Logger("app")
db = Logger("db")
app.lines.append("started")
print(app.lines, db.lines)
Output
initialising app
initialising db
['started'] []

More examples

Shared setup and super().__init__

Python
class Account:
def __init__(self, owner, opening=0):
self.owner = owner
self.history = []
self.balance = 0
if opening:
self.deposit(opening) # reuse a method during setup
def deposit(self, amount):
self.balance += amount
self.history.append(("deposit", amount))
class SavingsAccount(Account):
def __init__(self, owner, opening=0, rate=0.04):
super().__init__(owner, opening) # parent sets owner, history, balance
self.rate = rate
def add_interest(self):
self.deposit(round(self.balance * self.rate / 12, 2))
s = SavingsAccount("Asha", 12000)
s.add_interest()
print(s.owner, s.balance, s.rate)
print(s.history)
Output
Asha 12040.0 0.04
[('deposit', 12000), ('deposit', 40.0)]

Step-by-step explanation

  • Account.__init__ creates the history list before calling deposit, which depends on it.
  • SavingsAccount.__init__ calls super().__init__ first, then adds its own rate attribute.
  • add_interest reuses the inherited deposit method, so interest also appears in the history.

Expected output

Running “Shared setup and super().__init__” prints exactly:

TextOutput
Asha 12040.0 0.04
[('deposit', 12000), ('deposit', 40.0)]

Practical applications

  • Django models, dataclasses and GUI widgets all rely on __init__ (often generated or extended).
  • Subclasses of library classes must call super().__init__ to work correctly.

Best practices

  • Keep __init__ short: assign, validate, create containers.
  • Order attribute creation so methods called during setup work.
  • Always call super().__init__ when overriding in a subclass.

Common mistakes

Misspelling __init__

Avoid

def __int__(self, name): ... # or _init_

Prefer

def __init__(self, name): ...

A misspelt name is just an ordinary method, so arguments to the class raise TypeError.

Forgetting super().__init__

Avoid

class Savings(Account):
def __init__(self, owner, rate):
self.rate = rate # no owner, history or balance!

Prefer

class Savings(Account):
def __init__(self, owner, rate):
super().__init__(owner)
self.rate = rate

Overriding __init__ replaces the parent's; call it explicitly to keep its setup.

Important notes

  • The @dataclass decorator (module 17) can generate __init__ automatically for simple data classes.

Key takeaways

  • __init__ runs automatically after an object is created.
  • It sets the initial attributes from its parameters.
  • Subclasses call super().__init__ to reuse the parent's setup.

Try it yourself

  1. 1
    Write an Employee class whose __init__ computes an email address from first and last name.
  2. 2
    Create a Manager subclass that adds a team list and calls super().__init__.

Finished reading? Mark it complete to update your dashboard.

Suggested practice

16 questions cover the “Object-Oriented Programming” module. Answers and explanations are revealed after you submit.

  • ModerateWhat is printed?
  • ModerateWhat is printed?
  • ModerateWhat is printed?
Practise this module