What Are Those Underscores?

Any method (or other name) beginning and ending with two underscores is considered special by Python. The help documentation for strings shows these methods, among many others:

 | Methods defined here:
 |
 | __add__(...)
 | x.__add__(y) <==> x+y

These methods are typically connected with some other syntax in Python: use of that syntax will trigger a method call. For example, string method __add__ is called when anything is added to a string:

 >>>​​ ​​'TTA'​​ ​​+​​ ​​'GGG'
 'TTAGGG'
 >>>​​ ​​'TTA'​​.__add__(​​'GGG'​​)
 'TTAGGG'

Programmers almost never call these special methods directly, but is eye-opening to see this and may help you to understand how Python works.

Integers and floating-point numbers have ...

Get Practical Programming, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.