Special Methods

A Byte of Python 

Go to the Table of Contents. Visit the Gifcom web site.

Till now, we have covered majority of the various aspects of Python that you will use. In this chapter, we will cover some more aspects that will make our knowledge of Python more complete.

Special Methods

There are certain special methods which have special significance in classes such as the __init__ and __del__ methods whose significance we have already seen.

Generally, special methods are used to mimic certain behavior. For example, if you want to use the x[key] indexing operation for your class (just like you use for lists and tuples) then just implement the __getitem__() method and your job is done. If you think about it, this is what Python does for the list class itself!

Some useful special methods are listed in the following table. If you want to know about all the special methods, then a huge list is available in the Python Reference Manual.

Table 15.1. Some Special Methods

Name Explanation
__init__(self, ...) This method is called just before the newly created object is returned for usage.
__del__(self) Called just before the object is destroyed
__str__(self) Called when we use the print statement with the object or when str() is used.
__lt__(self, other) Called when the less than operator ( < ) is used. Similarly, there are special methods for all the operators (+, >, etc.)
__getitem__(self, key) Called when x[key] indexing operation is used.
__len__(self) Called when the built-in len() function is used for the sequence object.