liveBook · Manning

Special method

As explained in Get Programming: Learn to code with Python

A special method is a Python method with a predefined double-underscore name that is invoked implicitly by language syntax or explicitly as a regular method.

A special method is a regular Python method with a predefined name surrounded by double underscores. Language syntax or familiar functions can call it implicitly, while you can also call it explicitly like any other method. section 33.1 section 33.3

Special methods connect class objects to familiar Python operations:

  • __add__, __sub__, __mul__, and __truediv__ define mathematical operators such as +, -, *, and /. section 33.0
  • __str__ defines the text returned when Python uses print() or str() with an object. section 33.2

Adding fractions

A Fraction class can implement __add__ so that half + quarter returns a new Fraction representing 3/4. The method receives the other fraction, calculates a numerator and denominator, and returns a new object. Without __add__, Python raises a TypeError because it does not know how to add two Fraction objects. The same class can implement __mul__ for multiplication and __str__ so print(half) displays 1/2 instead of an object location. section 33.1 section 33.2

Table 33.1. A few special methods in Python

Category

Operator

Method name

Mathematical operations + - * / __add__ __sub__ __mul__ __truediv__
Comparisons == < > __eq__ __lt__ __gt__
Others print() and str() Create an object—for example, some_object = ClassName() __str__ __init__

Use the table to look up common special methods and the operators or functions they customize. section 33.1

The shorthand half + quarter is equivalent to half.__add__(quarter), or Fraction.__add__(half, quarter). This makes special methods ordinary methods with an additional, readable calling style. section 33.3

How Get Programming: Learn to code with Python covers it

How deep it goes
Explains naming, implementation, examples, errors, and equivalent calls, stopping short of a complete catalog of special methods.
Examples
Uses Fraction arithmetic, printed fractions, and suggested Circle and Stack string representations.
What it assumes
Assumes basic familiarity with classes and objects while defining the special-method pattern through small Fraction examples.
What you can do after
Build it from scratch by adding operator and string-display behavior to custom classes and rewriting shorthand calls explicitly.
How it connects
Connects classes with methods, operators, object initialization, string conversion, and function calls.

Also explained in

Compare how 3 books explain special 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.