ZetCode

Python __init__ Method

Last modified November 18, 2026 Python 3.15

Python calls __init__ to initialize a newly created object. The object itself is made by __new__; the initializer only fills in its state. This article shows the call order, the rules for self and return values, default values and their traps, validation, inheritance with super(), and alternative constructors.

What __init__ receives

Calling Person("Alice") goes through type.__call__, which first invokes __new__ and then passes the new object and the original arguments to __init__. The trace below makes that order explicit.

init_order.py
class Person:
    def __new__(cls, *args, **kwargs):
        print("__new__", cls.__name__)
        return super().__new__(cls)

    def __init__(self, name):
        print("__init__", name)
        self.name = name

    def __repr__(self):
        return f"Person({self.name!r})"


p = Person("Alice")
print(p)

The first parameter, conventionally called self, is the object returned by __new__. Attributes are stored on that object. If __new__ returned something that is not an instance of the class, __init__ would be skipped entirely.

$ python init_order.py
__new__ Person
__init__ Alice
Person('Alice')

The initializer must return None

__init__ is called for its side effects, not for a result. Returning any value raises TypeError; a bare return is fine because it returns None.

init_return.py
class Bad:
    def __init__(self):
        return 42


try:
    Bad()
except TypeError as e:
    print(type(e).__name__, e)

The error names the actual return type. This is a useful safety net: a typo that returns self or a computed value cannot silently change what a constructor call produces.

$ python init_return.py
TypeError __init__() should return None, not 'int'

Attributes and default values

Parameters with defaults make some arguments optional. The values are assigned to the instance in the usual way, and __repr__ makes the result easy to inspect.

init_defaults.py
class Car:
    def __init__(self, make, model, year=2023, color="black"):
        self.make = make
        self.model = model
        self.year = year
        self.color = color

    def __repr__(self):
        return f"{self.year} {self.make} {self.model} ({self.color})"


print(Car("Toyota", "Camry"))
print(Car("Ford", "Mustang", 2022, "red"))

The first car uses both defaults. The second supplies them positionally. Keyword arguments work as well: Car("Ford", "Mustang", color="blue") would keep the default year.

$ python init_defaults.py
2023 Toyota Camry (black)
2022 Ford Mustang (red)

Validating arguments

The initializer is the natural place to reject values that would leave a half-valid object. Raising before assigning means no instance escapes with bad state.

init_validation.py
class Age:
    def __init__(self, years):
        if years < 0:
            raise ValueError("age cannot be negative")
        self.years = years

    def __repr__(self):
        return f"Age({self.years})"


print(Age(30))
try:
    Age(-1)
except ValueError as e:
    print(type(e).__name__, e)

A valid Age is created normally. The negative value raises before self.years is set, so no partly initialized object can be used. Prefer a domain-specific exception to letting an invalid value reach later methods.

$ python init_validation.py
Age(30)
ValueError age cannot be negative

The mutable default trap

Default arguments are evaluated once, when the function is defined. A mutable default such as items=[] is therefore shared by every instance that leaves it out. Use None and create a fresh container inside the initializer.

init_mutable_default.py
class Wrong:
    def __init__(self, items=[]):
        self.items = items


a = Wrong()
b = Wrong()
a.items.append("x")
print(a.items, b.items, a.items is b.items)


class Right:
    def __init__(self, items=None):
        self.items = [] if items is None else list(items)


a = Right()
b = Right()
a.items.append("x")
print(a.items, b.items, a.items is b.items)

Both Wrong instances share one list. Right makes a new list for each instance, and also copies a supplied list so the caller's object is not adopted by reference.

$ python init_mutable_default.py
['x'] ['x'] True
['x'] [] False

Cooperative inheritance with super()

In a class hierarchy, each initializer should call super().__init__() so the other classes in the method resolution order get their turn. Passing keyword arguments along lets a diamond-shaped hierarchy cooperate.

init_super.py
class Base:
    def __init__(self, **kwargs):
        print("Base.__init__")
        super().__init__()


class Left(Base):
    def __init__(self, left, **kwargs):
        print("Left.__init__")
        self.left = left
        super().__init__(**kwargs)


class Right(Base):
    def __init__(self, right, **kwargs):
        print("Right.__init__")
        self.right = right
        super().__init__(**kwargs)


class Child(Left, Right):
    def __init__(self, **kwargs):
        print("Child.__init__")
        super().__init__(**kwargs)


c = Child(left=1, right=2)
print(c.left, c.right)

The method resolution order is Child, Left, Right, Base, object. Each class consumes its own keyword and forwards the rest, so every initializer runs exactly once. Calling Base.__init__ directly instead of super() would skip Right in this hierarchy.

$ python init_super.py
Child.__init__
Left.__init__
Right.__init__
Base.__init__
1 2

Alternative constructors

Python has only one initializer, but a @classmethod can offer other ways to build an instance. Such a factory creates the object through the class, so subclasses still get their own type.

init_factories.py
class Rectangle:
    def __init__(self, width, height):
        self.width = width
        self.height = height

    @classmethod
    def from_square(cls, side):
        return cls(side, side)

    @classmethod
    def from_dict(cls, data):
        return cls(data["width"], data["height"])

    def __repr__(self):
        return f"Rectangle({self.width}, {self.height})"


print(Rectangle(4, 5))
print(Rectangle.from_square(3))
print(Rectangle.from_dict({"width": 2, "height": 7}))

All three paths end in the same __init__. Keeping the parsing or conversion logic in the factory leaves the initializer small and gives callers descriptive names for common cases.

$ python init_factories.py
Rectangle(4, 5)
Rectangle(3, 3)
Rectangle(2, 7)

Positional-only and keyword-only parameters

A / marks parameters that must be passed by position, while a * marks those that must be passed by keyword. This gives the initializer a stable interface when defaults are added later.

init_parameters.py
class Point:
    def __init__(self, x, y, /, *, color="black"):
        self.x = x
        self.y = y
        self.color = color

    def __repr__(self):
        return f"Point({self.x}, {self.y}, {self.color!r})"


print(Point(1, 2))
print(Point(1, 2, color="red"))
try:
    Point(x=1, y=2)
except TypeError as e:
    print(type(e).__name__, e)

The coordinates are positional-only, so they cannot be supplied by name; color is keyword-only, so it cannot be passed as a third positional argument. This is a common shape for small value objects.

$ python init_parameters.py
Point(1, 2, 'black')
Point(1, 2, 'red')
TypeError Point.__init__() got some positional-only arguments passed as keyword arguments: 'x, y'

__new__ still creates the object

For most classes the inherited __new__ is enough. A subclass of an immutable built-in must override it, because the object cannot be changed after creation and __init__ receives the arguments unchanged.

init_tuple_subclass.py
class Pair(tuple):
    def __new__(cls, a, b):
        return super().__new__(cls, (a, b))

    def __init__(self, a, b):
        print("Pair.__init__", a, b)


p = Pair(1, 2)
print(p, type(p).__name__)

__new__ turns the two arguments into a two-element tuple. Python then calls __init__ with the original arguments, which are only used for the trace here. Assigning attributes in __init__ would fail because tuple instances are immutable.

$ python init_tuple_subclass.py
Pair.__init__ 1 2
(1, 2) Pair

Best practices

A few rules keep initializers predictable:

Source

object.__init__ - Python documentation

object.__new__ - Python documentation

Classes - Python tutorial

super() - Python documentation

In this article we have implemented the __init__ method. We have covered the call order with __new__, return values, defaults and their trap, validation, cooperative inheritance, factories, parameter kinds, and immutable subclasses. For related topics, see Python __new__ method, Python super() function, and Python dataclasses.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all Python tutorials.