next up previous contents
Next: Private Attributes Up: Writing Modules Previous: Classes and Object Oriented   Contents

Operator Overloading

Besides creating methods of our own, we can change the meaning of the way that many familiar operators work, a technique known as operator overloading. Special methods, whose names begin and end with double underscores, can be defined to ``intercept'' many common operators, allowing you to redefine what such operators as print, + and * or functions like len will do when they're applied to the objects you create. One of the most important operator overloading methods is the __init__ method. This method is called whenever the class name is used as a constructor, and allows you to initialize attributes in your object at the same time as you create it. The __str__ method is called through the print statement; the __repr__ method is called when an object's name is typed in the interpreter. Table 10.1 lists some of the more commonly used methods for overloading.

Table 10.1: Methods for Operator Overloading
Method Use  
__init__(object) called when class constructor is invoked  
__repr__(object) also called when object name typed in interpreter  
__del__(object) called when an object is destroyed  
__str__(object) called by print(object)  
__len__(object) called by len(object)  
__getitem__(object,key) allows you to intercept subscripting requests  
__setitem__(object,key,value) allows you to set values of subscripted items  
__getslice__(object,start,fin) allows you to intercept slice requests  
__setslice__(object,start,fin,value) allows you to set slices  
__add__(object,other) called by object + other  
__radd__(object,other) called by other + object  
__sub__(object,other) called by object - other  
__mul__(object,other) called by object * other  
__mod__(object,other) called by object % other  


In addition, you can define what happens when your object is iterated over by means of the for statement by defining an __iter__ method that simply returns the object itself, and providing a next method which will be called for each iteration. Inside the next method, you need to raise a StopIteration exception when no more items are available. (See Section 10.10 for an example.


next up previous contents
Next: Private Attributes Up: Writing Modules Previous: Classes and Object Oriented   Contents
Phil Spector 2003-11-12