liveBook · Manning

Constructor method

As explained in Get Programming: Learn to code with Python

A Python special method that is automatically invoked to initialize a newly created instance.

A constructor method is a special method that runs when an object is created. In Python, it is written as __init__ inside a class and usually sets the object's initial data attributes. section 31.2 section 31.7

class Circle(object):
    def __init__(self):
        self.radius = 0

This small Circle class gives each new object its own radius, initially set to zero through self.radius. section 31.2

The parameter self refers to the particular object being initialized. Writing self.radius creates an attribute that belongs to that object, so different objects can hold different values. section 31.2

Passing starting values

A Rectangle constructor can accept length and width: Rectangle(2, 4). Inside __init__, self.length = length and self.width = width preserve those values as attributes. Omitting a required value, as in Rectangle(2), raises a TypeError because width is missing. section 31.5

Remember these points:

  • Define __init__ inside a class to describe initial object setup. section 31.2
  • Use self.attribute to create or set data that persists for the object's lifetime. section 31.5
  • Supply every required constructor argument when creating an object. section 31.5

How Get Programming: Learn to code with Python covers it

How deep it goes
Explains class placement, self, attributes, parameters, and missing arguments through small Circle and Rectangle examples.
Examples
Uses Circle with a zero radius and Rectangle with length and width, including a missing-width TypeError.
What it assumes
Assumes basic familiarity with defining classes and objects while teaching methods, self, and data attributes directly.
What you can do after
Builds classes whose instances begin with chosen attributes and accepts required starting values.
How it connects
Connects classes, methods, object instances, data attributes, parameters, and dot notation.

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 Get Programming: Learn to code with Python. The section links point to the parts of the book it draws on.