Chapter 3. Usage Notes

This chapter includes usage notes that do not fit in other chapters.

Special Methods

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):  1
        return 0

cobj = C()

def mylen():
    return 1

cobj.__len__ = mylen 2

print len(cobj) 3



1

Usually we put the special methods in a class.

2

We can try to put them in the instance itself, but it doesn't work.

3

This goes straight to the class (calls C.__len__()), not to the instance.

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.

Example 3.2. Forwarding special method to instance

class C(object):
    def __len__(self):
        return self._mylen() 1

    def _mylen(self): 2
        return 0

cobj = C()

def mylen():
    return 1

cobj._mylen = mylen 3

print len(cobj) 4


1

We call another method on the instance,

2

for which we provide a default implementation in the class.

3

But it can be overwritten (rather hidden) by setting on the instance.

4

This now calls mylen().