page122.html

来自「Data Structures And Algorithms With Obje」· HTML 代码 · 共 46 行

HTML
46
字号
<HTML><HEAD><TITLE>Iterators and the Python for statement</TITLE></HEAD><BODY bgcolor="#FFFFFF"> <a href="../index.html" target="_top"><img src="../icons/usins.gif" alt="Logo" align=right></a><b>Data Structures and Algorithms with Object-Oriented Design Patterns in Python</b><br><A NAME="tex2html2616" HREF="page123.html"><IMG WIDTH=37 HEIGHT=24 ALIGN=BOTTOM ALT="next" SRC="../icons/next_motif.gif"></A> <A NAME="tex2html2614" HREF="page121.html"><IMG WIDTH=26 HEIGHT=24 ALIGN=BOTTOM ALT="up" SRC="../icons/up_motif.gif"></A> <A NAME="tex2html2610" HREF="page121.html"><IMG WIDTH=63 HEIGHT=24 ALIGN=BOTTOM ALT="previous" SRC="../icons/previous_motif.gif"></A>  <A NAME="tex2html2618" HREF="page611.html"><IMG WIDTH=43 HEIGHT=24 ALIGN=BOTTOM ALT="index" SRC="../icons/index_motif.gif"></A> <BR><HR><H3><A NAME="SECTION005241000000000000000">Iterators and the Python <tt>for</tt> statement</A></H3><P>The Python compiler automatically generates code to use an iteratorwhen the <tt>for</tt> statement is used.Thus, given an object <tt>c</tt> that is an instance ofa concrete class <tt>SomeContainer</tt>derived from the abstract <tt>Container</tt> base class,we can use the <tt>for</tt> statement to enumerate the objectsin the container as follows:<PRE>c = new SomeContainer();# ...for obj in c:    print obj</PRE><P>One of the advantages of using an iterator object thatis separate from the container is that it is possibleto have more than one iterator associated with a given container.For example, consider the following code fragment:<PRE>c = SomeContainer()# ...for obj1 in c:    for obj2 in c:	if obj1 == obj2:	    print obj1, obj2</PRE>This code implicitly uses two distinct iterators,one for each <tt>for</tt> loop.This code compares all ordered-pairs of objects in the container <tt>c</tt>and prints out those which are equal.<P><HR><A NAME="tex2html2616" HREF="page123.html"><IMG WIDTH=37 HEIGHT=24 ALIGN=BOTTOM ALT="next" SRC="../icons/next_motif.gif"></A> <A NAME="tex2html2614" HREF="page121.html"><IMG WIDTH=26 HEIGHT=24 ALIGN=BOTTOM ALT="up" SRC="../icons/up_motif.gif"></A> <A NAME="tex2html2610" HREF="page121.html"><IMG WIDTH=63 HEIGHT=24 ALIGN=BOTTOM ALT="previous" SRC="../icons/previous_motif.gif"></A>  <A NAME="tex2html2618" HREF="page611.html"><IMG WIDTH=43 HEIGHT=24 ALIGN=BOTTOM ALT="index" SRC="../icons/index_motif.gif"></A> <P><ADDRESS><img src="../icons/bruno.gif" alt="Bruno" align=right><a href="../copyright.html">Copyright &#169; 2003</a> by <a href="../signature.html">Bruno R. Preiss, P.Eng.</a>  All rights reserved.</ADDRESS></BODY></HTML>

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?