Skip to main content
Beginnerconceptual

What is the __init__ method in Python, and what are self and the pass keyword used for?

ReportedSource: GeeksforGeeks interview experience: Cognizant GenC 2024

Quick answer

__init__ initialises a new instance's attributes (called after __new__); self is the instance passed explicitly to methods; pass is a no-op placeholder where a block is syntactically required.

__init__ is the initialiser called automatically after a new instance is created; it sets up instance attributes. (The object itself is created by __new__, which you rarely override.)

main.py
class Student:
    school = 'ABC School'           # class attribute, shared

    def __init__(self, name, marks=0):
        self.name = name            # instance attributes
        self.marks = marks

    def grade(self):
        return 'A' if self.marks >= 90 else 'B'

s = Student('Asha', 92)

self is the instance the method is called on. Python passes it explicitly as the first parameter (s.grade() is Student.grade(s)); the name is a convention.

pass is a no-op statement used where syntax needs a block but you have nothing to run yet:

main.py
class PaymentError(Exception):
    pass

def todo():
    pass

Related follow-ups. Python has no constructor overloading (use default arguments or @classmethod factories); super().__init__() calls the parent initialiser in inheritance.

Discussion