liveBook · Manning

Operator

As explained in Get Programming: Learn to code with Python

An operator is a symbolic element of Python syntax that specifies an operation on one or more values or objects.

An operator is a symbol in Python syntax that specifies an operation on values or objects. Operators are shorthand: each operation is implemented as a method for the relevant object type. section 33.0 section 33.1

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__

Common operator symbols map to special-method names, such as + to __add__ and * to __mul__. section 33.1

Adding fractions

Python cannot add two Fraction objects until the class defines the operation. Implementing __add__ lets the + operator combine their numerators and denominators and return a new Fraction. section 33.1

Operators also help with practical calculations: dividing minutes by 60 gives decimal hours, while the remainder operator (%) provides another way to find leftover minutes. section 6.3

How Get Programming: Learn to code with Python covers it

How deep it goes
Defines operators as shorthand for object methods and works through Fraction addition, while noting many special methods remain unlisted.
Examples
Demonstrates hours-to-minutes arithmetic, Fraction addition, and midpoint calculations for names.
What you can do after
Build custom operator behavior by implementing special methods such as __add__, and calculate whole hours or leftover minutes.
How it connects
Connects operators with classes, objects, and special methods.

Also explained in

Compare how 7 books explain operator →

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.