This chapter includes usage notes that do not fit in other chapters.
In Python, we can use methods with special name like
__add__() to make objects convenient to use (for
example, with the built-in functions
str() or with the '
Example 3.1. Special methods work on type only
Usually we put the special methods in a class.
We can try to put them in the instance itself, but it doesn't work.
straight to the class (calls
The same is true for all such methods, putting them on the instance we
want to use them with does not work. If it did go to the instance then
even something like
of the class
C) would go to
C.__str__(), which is a method defined for an
C, and not
A simple technique to allow defining such methods for each instance separately is shown below.
Example 3.2. Forwarding special method to instance