liveBook · Manning

Constructor method

As explained in Python Workout, Second Edition

The __init__ method is Python's special instance-initialization method, called after an object is created to initialize its attributes.

In Python, __init__ initializes an instance after __new__ creates it and before the instance is returned. It receives the new object as self and assigns attributes such as self.flavor. section 10.6 section 10.8

Use __init__ to:

  • Accept arguments passed when the class is called and store them as instance attributes. section 10.6
  • Initialize shared parent-class state through super().__init__ rather than duplicating assignments. section 10.16 section 10.26
  • Provide defaults or initialize resources, such as a default beverage temperature or an opened file attribute. section 10.8

A subclass delegates initialization

class Person: def __init__(self, name): self.name = name class Employee(Person): def __init__(self, name, id_number): super().__init__(name) self.id_number = id_number Employee('empname', 1) The subclass adds id_number while letting Person initialize name. Without the super call, the parent __init__ does not automatically run merely because the subclass defines its own __init__. section 10.16

When we create an object, __new__ is invoked.
sidebar figure

Trace the object-creation sequence: __new__ creates the object, __init__ adds its attributes, and the completed object is returned. section 10.8

How Python Workout, Second Edition covers it

How deep it goes
Explains attribute assignment, self, inheritance, super, and the __new__ distinction, while stopping short of implementing __new__.
Examples
Uses Scoop, Person, Employee, Animal subclasses, beverages, files, and a Cage to demonstrate initialization choices.
What it assumes
Assumes familiarity with classes and methods while establishing self, instance attributes, and class-call behavior.
What you can do after
Build instance initialization, delegate parent setup with super, and distinguish initialization from object creation.
How it connects
Connects instance attributes with classes, self, inheritance, super, and __new__.

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 Python Workout, Second Edition. The section links point to the parts of the book it draws on.