12.07.2015 Views

Is Python a

Is Python a

Is Python a

SHOW MORE
SHOW LESS
  • No tags were found...

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

All operator overloading methods are optional—if you don’t code one, that operationis simply unsupported by your class (and may raise an exception if attempted).Most overloading methods are used only in advanced programs that require objectsto behave like built-ins; the _ _init_ _ constructor tends to appear in most classes,however. We’ve already met the _ _init_ _ initialization-time constructor method,and a few of the others in Table 24-1. Let’s explore some of the additional methodsin the table by example._ _getitem_ _ Intercepts Index ReferencesThe _ _getitem_ _ method intercepts instance-indexing operations. When an instanceX appears in an indexing expression like X[i], <strong>Python</strong> calls the _ _getitem_ _ methodinherited by the instance (if any), passing X to the first argument, and the index inbrackets to the second argument. For instance, the following class returns the squareof an index value:>>> class indexer:... def _ _getitem_ _(self, index):... return index ** 2...>>> X = indexer( )>>> X[2] # X[i] calls _ _getitem_ _(X, i).4>>> for i in range(5):... print X[i],...0 1 4 9 16_ _getitem_ _ and _ _iter_ _ Implement IterationHere’s a trick that isn’t always obvious to beginners, but turns out to be incredibly useful.The for statement works by repeatedly indexing a sequence from zero to higherindexes, until an out-of-bounds exception is detected. Because of that, _ _getitem_ _also turns out to be one way to overload iteration in <strong>Python</strong>—if this method is defined,for loops call the class’ _ _getitem_ _ each time through, with successively higher offsets.It’s a case of “buy one, get one free”—any built-in or user-defined object thatresponds to indexing also responds to iteration:>>> class stepper:... def _ _getitem_ _(self, i):... return self.data[i]...>>> X = stepper( ) # X is a stepper object>>> X.data = "Spam">>>>>> X[1] # Indexing calls _ _getitem_ _'p'>>> for item in X: # for loops call _ _getitem_ _... print item, # for indexes items 0..N...S p a mOperator Overloading | 493

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!