Operator Overloading
User-defined objects can be made to work with all of Python’s built-in operators by adding implementations of the special methods described in Chapter 3 to a class. For example, if you wanted to add a new kind of number to Python, you could define a class in which special methods such as __add__() were defined to make instances work with the standard mathematical operators.
The following example shows how this works by defining a class that implements the complex numbers with some of the standard mathematical operators and type-coercion methods to allow complex numbers to be mixed with integers and floats. Note that because Python already provides a complex number type, this class is only provided for the purpose of illustration. ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access