Defining __init__

suggest change

In Python, the __init__ method is the instance initializer. When you instantiate a class (e.g. user = User("Alice")), Python first calls __new__ to allocate the object in memory, and then immediately invokes __init__ to configure the instance's initial attributes.


1. Basic Structure and the self Parameter

The first parameter of __init__ is always self, which represents the newly created object instance. Any parameters passed during instantiation are forwarded to __init__:

class User:
    def __init__(self, username: str, email: str):
        # Bind attributes to the instance
        self.username = username
        self.email = email
        self.is_active = True  # Default state

# Instantiating the class invokes __init__
alice = User("alice", "alice@example.com")

print(alice.username)   # Output: alice
print(alice.is_active)  # Output: True

The Return Value Rule

__init__ must never return any value other than None. Returning anything else raises a runtime TypeError:

class BadClass:
    def __init__(self):
        return "something"  # Raises TypeError: __init__() should return None, not 'str'

2. Optional Arguments and the Mutable Default Trap

You can provide default values for arguments in __init__:

class Server:
    def __init__(self, host: str = "127.0.0.1", port: int = 8080):
        self.host = host
        self.port = port

The Mutable Default Argument Pitfall

Never use mutable objects (such as list, dict, or set) as default values in __init__. Default argument expressions are evaluated once at function definition time, meaning all instances that use the default will share the exact same list in memory:

# BUGGY: Every student shares the same list!
class Student:
    def __init__(self, name: str, grades: list = []):
        self.name = name
        self.grades = grades

s1 = Student("Alice")
s1.grades.append(95)

s2 = Student("Bob")
print(s2.grades)  # Output: [95] - Bob inherited Alice's grades!

The Idiomatic Fix (None Sentinel)

Default the argument to None and instantiate a fresh list inside the method body:

class Student:
    def __init__(self, name: str, grades: list | None = None):
        self.name = name
        # If None, allocate a new list unique to this instance
        self.grades = [] if grades is None else list(grades)

s1 = Student("Alice")
s1.grades.append(95)

s2 = Student("Bob")
print(s2.grades)  # Output: [] (Correctly isolated)

3. Inheritance and super().__init__()

When subclassing a parent class and defining a custom __init__, you must explicitly call super().__init__(...) to ensure the parent's attributes are initialized:

class Animal:
    def __init__(self, name: str, species: str):
        self.name = name
        self.species = species

class Dog(Animal):
    def __init__(self, name: str, breed: str):
        # 1. Initialize parent attributes
        super().__init__(name=name, species="Canine")
        # 2. Initialize subclass-specific attributes
        self.breed = breed

buddy = Dog("Buddy", "Golden Retriever")
print(f"{buddy.name} is a {buddy.species} of breed {buddy.breed}")
# Output: Buddy is a Canine of breed Golden Retriever

If you omit super().__init__(), attributes defined in the parent class (like self.name and self.species) will never be created on the instance, leading to AttributeError when accessed.


4. Input Validation and Invariant Enforcement

__init__ is the ideal location to validate data integrity before allowing the object to exist in an invalid state:

class BankAccount:
    def __init__(self, account_number: str, initial_balance: float = 0.0):
        if not account_number.isalnum():
            raise ValueError("Account number must be alphanumeric")
        if initial_balance < 0:
            raise ValueError("Initial balance cannot be negative")

        self.account_number = account_number
        self.balance = float(initial_balance)

Raising exceptions in __init__ enforces fail-fast design: invalid objects are rejected before they propagate through the application.


5. Modern Alternative: dataclasses

Writing boilerplate __init__ methods that simply assign arguments to self can be automated with Python's standard dataclasses module (introduced in Python 3.7):

from dataclasses import dataclass, field

@dataclass
class Product:
    name: str
    price: float
    tags: list[str] = field(default_factory=list)

    # Custom post-initialization validation
    def __post_init__(self):
        if self.price < 0:
            raise ValueError("Price cannot be negative")

laptop = Product(name="ThinkPad", price=1299.99, tags=["electronics", "computers"])
print(laptop)
# Output: Product(name='ThinkPad', price=1299.99, tags=['electronics', 'computers'])

@dataclass automatically generates __init__, __repr__, __eq__, and properly handles mutable defaults via default_factory.


Best Practices

  1. Keep __init__ Lightweight: __init__ should set up instance variables and validate parameters. Avoid expensive I/O operations (network requests, disk reading) inside __init__; use factory methods or explicit connection methods instead.
  2. Always Use None as Default for Mutables: Prevent unintentional state sharing across instances by using None and initializing inside the method.
  3. Always Call super().__init__() in Subclasses: Ensure base classes are properly configured before executing derived logic.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents