liveBook · Manning

Constructor method

As explained in Practices of the Python Pro

__init__ is the Python instance initializer method that sets up an object's initial state after the instance has been constructed.

__init__() is Python’s instance initializer. It runs after an object has been constructed and sets up the object’s initial state. It receives self, a reference to the new instance, plus any arguments needed to establish its attributes. section 2.2.2

A class groups related data and behavior: attributes hold state, while methods can access or change it through self. Creating an instance resembles calling a function, with arguments passed to __init__ excluding self. section 2.2.2

Initializing a game simulator

class RockPaperScissorsSimulator:\n def __init__(self):\n self.computer_choice = None\n self.human_choice = None\n\nRPS = RockPaperScissorsSimulator()\nRPS.simulate()\n\nThe initializer gives both choices a known starting state; later methods update and read those attributes through self.

How Practices of the Python Pro covers it

How deep it goes
Defines initialization, self, arguments, and instance creation, then demonstrates attribute updates; it stops short of advanced initialization patterns.
Examples
Uses a RockPaperScissorsSimulator whose initializer sets human_choice and computer_choice to None.
What it assumes
Assumes basic Python classes and functions while teaching instance state, self, methods, and initializer behavior.
What you can do after
Build instances with predictable starting attributes and let methods access or change that state through self.
How it connects
Connects __init__() with classes, objects, instances, attributes, methods, and constructors.

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 Practices of the Python Pro. The section links point to the parts of the book it draws on.