Python / Core Python Fundamentals Interview Questions
How do you define a class in Python, and what is the role of __init__?
A class is a blueprint for objects. Define it with the class keyword. The special method __init__ (the constructor) is called automatically when you create an instance and is where you set up the object's initial state by assigning to self.attribute.
class BankAccount: interest_rate = 0.03 # class attribute â shared by all instances def __init__(self, owner, balance=0): self.owner = owner # instance attributes self.balance = balance def deposit(self, amount): if amount <= 0: raise ValueError('Deposit amount must be positive') self.balance += amount def __repr__(self): return f'BankAccount({self.owner!r}, balance={self.balance})' acc = BankAccount('Alice', 1000) acc.deposit(500) print(acc) # BankAccount('Alice', balance=1500) print(acc.interest_rate) # 0.03
self is a reference to the current instance; it is not a keyword but the universal convention. Every instance method receives it as the first parameter. Class attributes are defined directly in the class body and shared across all instances; instance attributes are set with self.attr = value inside methods and belong to each object individually.
Important dunder methods to know: __str__ (readable string for end users, called by print), __repr__ (unambiguous string for developers, called in the REPL), __len__, __eq__, __lt__, and __enter__/__exit__ for context managers.
More Related questions...