liveBook · Manning

Constructor method

As explained in The Quick Python Book, Fourth Edition

__init__ is Python's conventional instance-initialization method invoked when an object is initialized.

Define `__init__` in a Python class to initialize each new instance. Python calls it when an instance is created, passing that instance as the first argument, conventionally named `self`. Despite its common label of “constructor,” `__init__` initializes an object; `__new__` creates it. Override `__new__` only for less common cases, such as subclassing an immutable type. section 15.1.1

Initialize a field

class Circle: def __init__(self, radius=1): self.radius = radius small = Circle() large = Circle(5) print(small.radius, large.radius) # 1 5 The default supplies a value when no argument is given. Assigning to `self.radius` creates the field on that instance; it can be changed later. section 15.1.1 section 15.8

Two practical rules:

  • A subclass initializer must explicitly call its base-class initializer when it needs that initialization. For example, `super().__init__(x, y)` can set inherited position fields before the subclass sets its own radius. section 3.6 section 15.8
  • Overriding `__setitem__` in a `dict` subclass does not check every way to populate it: initial key-value pairs can bypass that method. Override `__init__` too if initial contents need validation; one approach calls the parent initializer and then checks `self`. section 17.11

A Python class has only one `__init__` method. The similarly named `__init__.py` is a package file, not an instance initializer. section 15.1.1 section 18.6.2

How The Quick Python Book, Fourth Edition covers it

How deep it goes
Explains automatic invocation, `self`, defaults, subclass calls, and the distinction from `__new__`; leaves unusual object-creation overrides aside.
Examples
Shows circles initialized with default or supplied values, inherited position fields, and a string-only dictionary requiring initial validation.
What it assumes
Assumes general object-oriented programming familiarity while spelling out Python’s `self` convention and instance-initialization behavior.
What you can do after
Build it from scratch: write an initializer that sets instance fields, calls a base initializer when needed, and checks initial dictionary contents.
How it connects
Connects instance attributes and inheritance to `super()`, `__new__`, and dictionary subclassing.

Also explained in

Compare how 13 books explain constructor method →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of The Quick Python Book, Fourth Edition. The section links point to the parts of the book it draws on.