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


