file-fusion.com → best online → python class free → init method in python
Posted on by Jeffrey Sutton

init method in python

Code snippet showing Python class with __init__ method on a dark terminal background

The init method in Python is a special function automatically called when a new instance of a class is created. It sets up initial values for object attributes and runs once per object.

Every time you write MyClass(), Python checks for a method named __init__ inside the class. If it exists, Python calls it with the new object as the first argument (conventionally named self). This allows you to assign values to instance variables before the object is fully constructed.

For example, creating a Person object with a name and age uses __init__ to store those values:

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

person = Person("Alice", 30)
print(person.name)  # Output: Alice
print(person.age)   # Output: 30

This method is part of Python's dunder (double show) system. Dunder methods define behavior for operators, built-ins, and object lifecycle events. The __init__ method specifically controls object setup during instantiation.

How it works

When you call a class like Person("Bob", 25), Python performs several steps behind the scenes. First, it creates an empty instance of the class. Then it passes that instance as the first argument to __init__.

The method receives the instance (self), plus any arguments passed during creation. Inside the method, you assign values to attributes using dot notation. These attributes become part of the object's state.

After __init__ finishes, Python returns the initialized object. You can then access the stored values through the object's attributes.

Example: A BankAccount class uses __init__ to set a starting balance and account holder:

class BankAccount:
    def __init__(self, owner, balance=0):
        self.owner = owner
        self.balance = balance

account = BankAccount("Charlie", 1000)
print(account.owner)  # Charlie
print(account.balance)  # 1000

If no balance is given, the default value of 0 is used. This shows how __init__ supports optional parameters.

Types and variations

There are no distinct "types" of __init__, but it can be written in different ways depending on the class design. The most common patterns are:

Pattern Use Case Example
Basic initialization Setting required attributes def __init__(self, name)
Default values Optional parameters def __init__(self, name, age=18)
Validation Checking input before assignment if age < 0: raise ValueError
Complex setup Initializing internal structures self.accounts = []

Some classes use __init__ to perform setup beyond attribute assignment. For example, a DatabaseConnection class might open a socket or load configuration files during initialization.

A common mistake is returning a value from __init__. The method must return None. Returning anything else causes a TypeError when instantiating the class.

Common confusions and corrections

Many beginners think __init__ is the constructor. That's incorrect. Python doesn't have constructors like Java or C++. Instead, it uses two separate steps: object creation and initialization.

Python first calls __new__ to create the instance, then calls __init__ to initialize it. You rarely override __new__, but you can if you need custom object creation logic.

Another misconception is that __init__ runs every time you access an attribute. It does not. It runs only once, when the object is created. After that, attribute access is direct and fast.

Some developers assume __init__ is required. It isn't. A class can exist without it. If missing, the object still gets created, but no initialization happens. Attributes must be added later.

Example: A Point class without __init__:

class Point:
    pass

p = Point()
p.x = 5
p.y = 10
print(p.x, p.y)  # 5 10

This works but is error-prone. Always define __init__ to ensure consistent object state.

Real-world usage and best practices

Use __init__ to enforce valid object states. For example, a Temperature class should validate that the value is within physical limits:

class Temperature:
    def __init__(self, celsius):
        if celsius < -273.15:
            raise ValueError("Temperature below absolute zero")
        self.celsius = celsius

According to the official Python tutorial, defining __init__ makes your classes predictable and reusable. It ensures every instance starts with the same expected structure.

I once built a configuration loader that used __init__ to parse JSON files and set environment variables. Without __init__, I'd have had to manually assign each setting after loading. The method reduced boilerplate and caught invalid inputs early.

Always use descriptive parameter names. Avoid single-letter variables unless they're standard (like i in loops). Name parameters so users understand their purpose.

Do not use mutable objects as default arguments. This is a well-known bug. Example:

class BadClass:
    def __init__(self, items=[]):  # ❌ Dangerous
        self.items = items

obj1 = BadClass()
obj1.items.append("first")
obj2 = BadClass()
print(obj2.items)  # ['first'] - unexpected!

Instead, use None and assign a new list inside the method:

class GoodClass:
    def __init__(self, items=None):
        self.items = items or []

This avoids shared state between instances. The Python documentation warns against this pattern in Python Guide: Gotchas.

What it's not

The __init__ method is not a destructor. That role belongs to __del__, which runs when an object is garbage collected. It's also not called when you modify an attribute later. Only instantiation triggers it.

It's not the same as a static method. Static methods don't receive self and can't access instance data. They're useful for utility functions related to the class but not tied to any specific object.

Finally, __init__ is not the only dunder method. Others include __str__ (for string representation), __repr__ (for debugging), and __eq__ (for equality comparison). Each handles a different aspect of object behavior.

Understanding __init__ correctly prevents bugs and improves code clarity. It's the foundation of object-oriented design in Python.

Now that you know how the init method in python works, you can build classes that start in a known, valid state. Use it to set up attributes, validate inputs, and avoid errors downstream.


Related Posts