This chapter includes usage notes that do not fit in other chapters.
In Python, we can use methods with special name like
__len__(), __str__() and
__add__() to make objects convenient to use (for
example, with the built-in functions len(),
str() or with the '+' operator,
etc.)
Example 3.1. Special methods work on type only
class C(object):
def __len__(self):
return 0
cobj = C()
def mylen():
return 1
cobj.__len__ = mylen
print len(cobj)
| Usually we put the special methods in a class. |
| We can try to put them in the instance itself, but it doesn't work. |
| This goes
straight to the type (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 str(C) (str
of the class C) would go to
C.__str__(), which is a method defined for an
instance of C, and not
C itself.
A simple technique to allow defining such methods for each instance separately is shown below.