August 2019
Beginner
482 pages
12h 56m
English
In Python, when we add two numbers, what is happening under the hood is that one of them is calling its method on the other.
Consider the following example:
>>> 1 + 23
Here, under the hood, 1 is calling its __add__ method on 2. Inside, 1 is checking whether 2 is of a supported type, and runs the computation.
We don't want to mess with number behavior, but this process is exactly the same for any custom class as well. In other words, if you define the __add__ function of your class, you'll be able to add something to this class. In some cases, you might try to add something that your class doesn't know how to handle. It should then raise a built-in notImplemented exception. In this case, Python will try ...