Object-Oriented Programming
__init__ Method
Object initialization and constructor patterns
Interview: Critical interview topic — understanding __init__ vs __new__, constructor overloading patterns, and initialization best practices
The __init__ method is Python's constructor — it's automatically called when a new object is created. It initializes the object's attributes and sets up its initial state. Understanding __init__ deeply is crucial for effective OOP in Python.
How __init__ Works
__init__is called after__new__creates the instance- The first parameter is always
self(the newly created instance) - It should return
None— returning anything else raisesTypeError - It can accept any parameters to customize initialization
- Default values,
args, and*kwargsare all supported
__init__ vs __new__
This is a common interview question. __new__ is responsible for creating the instance, while __init__ is responsible for initializing it. In most cases, you only need __init__. Use __new__ only for immutable types or metaclass programming.
Constructor Patterns
Python doesn't support method overloading, so you can't have multiple __init__ methods. Instead, use default arguments, args/*kwargs, or @classmethod factory methods to provide alternative constructors.
Interview Tip
Be prepared to explain the Singleton pattern using __new__, and know when __init__ gets called multiple times (hint: it can happen with __new__ returning an existing instance).
Use Cases
Initializing object state with required and optional parameters
Implementing Singleton pattern with __new__
Creating factory methods with @classmethod for alternative constructors
Validating input data during object creation
Setting up database connections or file handles in constructors
Common Mistakes
Returning a value from __init__ (other than None) causes TypeError
Using mutable defaults in __init__ parameters (e.g., items=[]) — shared across calls
Forgetting to call super().__init__() in subclass constructors
Confusing __new__ (creates instance) with __init__ (initializes instance)
__init__ is called every time you call the class, even if __new__ returns existing instance