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.

In fact, it’s really a case of “buy one, get a bunch free.” Any class that supports forloops automatically supports all iteration contexts in <strong>Python</strong>, many of which we’veseen in earlier chapters (see Chapter 13 for other iteration contexts). For example,the in membership test, list comprehensions, the map built-in, list and tuple assignments,and type constructors will also call _ _getitem_ _ automatically, if it’s defined:>>> 'p' in X # All call _ _getitem_ _ too1>>> [c for c in X] # List comprehension['S', 'p', 'a', 'm']>>> map(None, X) # map calls['S', 'p', 'a', 'm']>>> (a, b, c, d) = X # Sequence assignments>>> a, c, d('S', 'a', 'm')>>> list(X), tuple(X), ''.join(X)(['S', 'p', 'a', 'm'], ('S', 'p', 'a', 'm'), 'Spam')>>> XIn practice, this technique can be used to create objects that provide a sequenceinterface and to add logic to built-in sequence type operations; we’ll revisit this ideawhen extending built-in types in Chapter 26.User-Defined IteratorsToday, all iteration contexts in <strong>Python</strong> will try the _ _iter_ _ method first, before trying_ _getitem_ _. That is, they prefer the iteration protocol we learned about inChapter 13 to repeatedly indexing an object; if the object does not support the iterationprotocol, indexing is attempted instead.Technically, iteration contexts work by calling the iter built-in function to try tofind an _ _iter_ _ method, which is expected to return an iterator object. If it’s provided,<strong>Python</strong> then repeatedly calls this iterator object’s next method to produceitems until a StopIteration exception is raised. If no such _ _iter_ _ method is found,<strong>Python</strong> falls back on the _ _getitem_ _ scheme, and repeatedly indexes by offsets asbefore, until an IndexError exception is raised.In the new scheme, classes implement user-defined iterators by simply implementingthe iterator protocol introduced in Chapters 13 and 17 (refer back to those chaptersfor more background details on iterators). For example, the following file, iters.py,defines a user-defined iterator class that generates squares:class Squares:def _ _init_ _(self, start, stop):self.value = start - 1self.stop = stop494 | Chapter 24: Class Coding Details# Save state when created

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

Saved successfully!

Ooh no, something went wrong!