liveBook · Manning

Constructor method

As explained in Python Workout: 50 ten-minute exercises

__init__ is a Python instance method that initializes an object during instance creation.

__init__() initializes an already-created Python instance by assigning attributes from the arguments passed to the class call. When Python evaluates Person('Ada'), __new__ creates the object, then __init__ receives it as self before the instance is returned. section 9.2 section 9.5

Use __init__() to:

  • Create instance attributes such as self.name or self.flavor. section 9.2
  • Accept required arguments or provide defaults when constructing instances. section 9.5
  • Initialize shared state in a parent class and extend it in subclasses. section 9.15 section 9.27

Initialize and extend an instance

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 e = Employee('Ada', 1) The subclass must initialize its own attributes and does not automatically execute the parent’s __init__(). Calling super().__init__(name) reuses the parent initialization without naming the parent class directly. section 9.15 section 9.27

class Employee(Person)
    def __init__(self, name, id_number):
        super().__init__(name)           #1
        self.id_number = id_number

Compare subclass initialization with super().__init__ and see where each attribute is assigned. section 9.15

The first parameter is conventionally named self; Python passes the instance there, but self is not a reserved word. The method is commonly called a constructor, although __new__ performs object creation and __init__ performs initialization. section 9.2 section 9.5

How Python Workout: 50 ten-minute exercises covers it

How deep it goes
Explains execution order, self, attributes, defaults, inheritance, and super, while stopping short of implementing __new__.
Examples
Uses Scoop, Person, Employee, Animal, Beverage, and LogFile examples to demonstrate attributes, inheritance, defaults, and resources.
What it assumes
Assumes familiarity with Python functions and classes while teaching instance attributes, self, and the distinction between __new__ and __init__.
What you can do after
Build it from scratch by defining classes that validate arguments informally, assign instance attributes, and delegate shared setup with super().
How it connects
Connects instance attributes, classes, object creation, 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: 50 ten-minute exercises. The section links point to the parts of the book it draws on.