Software: Apache/2.0.54 (Unix) mod_perl/1.99_09 Perl/v5.8.0 mod_ssl/2.0.54 OpenSSL/0.9.7l DAV/2 FrontPage/5.0.2.2635 PHP/4.4.0 mod_gzip/2.0.26.1a uname -a: Linux snow.he.net 4.4.276-v2-mono-1 #1 SMP Wed Jul 21 11:21:17 PDT 2021 i686 uid=99(nobody) gid=98(nobody) groups=98(nobody) Safe-mode: OFF (not secure) /usr/doc/python-2.2.3/html/whatsnew/ drwxr-xr-x | |
| Viewing file: Select action/file-type: 3 PEP 234: IteratorsAnother significant addition to 2.2 is an iteration interface at both the C and Python levels. Objects can define how they can be looped over by callers.
In Python versions up to 2.1, the usual way to make
__getitem__() is more properly used to define an indexing
operation on an object so that you can write
In Python 2.2, iteration can be implemented separately, and
__getitem__() methods can be limited to classes that really
do support random access. The basic idea of iterators is
simple. A new built-in function, iter(obj) or
Python classes can define an __iter__() method, which should
create and return a new iterator for the object; if the object is its
own iterator, this method can just return So, after all this, what do iterators actually do? They have one required method, next(), which takes no arguments and returns the next value. When there are no more values to be returned, calling next() should raise the StopIteration exception.
In 2.2, Python's for statement no longer expects a sequence;
it expects something for which iter() will return an iterator.
For backward compatibility and convenience, an iterator is
automatically constructed for sequences that don't implement
__iter__() or a tp_iter slot, so
Iterator support has been added to some of Python's basic types. Calling iter() on a dictionary will return an iterator which loops over its keys:
That's just the default behaviour. If you want to iterate over keys,
values, or key/value pairs, you can explicitly call the
iterkeys(), itervalues(), or iteritems()
methods to get an appropriate iterator. In a minor related change,
the in operator now works on dictionaries, so
Files also provide an iterator, which calls the readline() method until there are no more lines in the file. This means you can now read each line of a file using code like this:
Note that you can only go forward in an iterator; there's no way to get the previous element, reset the iterator, or make a copy of it. An iterator object could provide such additional capabilities, but the iterator protocol only requires a next() method.
See Also:
See About this document... for information on suggesting changes. |
:: Command execute :: | |
--[ c99shell v. 1.0 pre-release build #13 powered by Captain Crunch Security Team | http://ccteam.ru | Generation time: 0.0183 ]-- |