﻿<?xml version="1.0" encoding="utf-8" standalone="yes"?><rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:trackback="http://madskills.com/public/xml/rss/module/trackback/" xmlns:wfw="http://wellformedweb.org/CommentAPI/" xmlns:slash="http://purl.org/rss/1.0/modules/slash/"><channel><title>C++博客-Welcome to 陈俊峰's ---BeetleHeaded Man Blog !-随笔分类-Python</title><link>http://www.cppblog.com/Jeff-Chen/category/1412.html</link><description /><language>zh-cn</language><lastBuildDate>Mon, 26 May 2008 12:07:21 GMT</lastBuildDate><pubDate>Mon, 26 May 2008 12:07:21 GMT</pubDate><ttl>60</ttl><item><title>python的对象与名字绑定（转贴，此文甚好,红字部分为经典说明）</title><link>http://www.cppblog.com/Jeff-Chen/archive/2006/04/17/5785.html</link><dc:creator>Jeff-Chen</dc:creator><author>Jeff-Chen</author><pubDate>Mon, 17 Apr 2006 11:27:00 GMT</pubDate><guid>http://www.cppblog.com/Jeff-Chen/archive/2006/04/17/5785.html</guid><wfw:comment>http://www.cppblog.com/Jeff-Chen/comments/5785.html</wfw:comment><comments>http://www.cppblog.com/Jeff-Chen/archive/2006/04/17/5785.html#Feedback</comments><slash:comments>0</slash:comments><wfw:commentRss>http://www.cppblog.com/Jeff-Chen/comments/commentRss/5785.html</wfw:commentRss><trackback:ping>http://www.cppblog.com/Jeff-Chen/services/trackbacks/5785.html</trackback:ping><description><![CDATA[
		<div class="post">
				<h2>
						<a id="viewpost1_TitleUrl" href="http://sirsunny.cnblogs.com/archive/2005/06/25/180898.html">python的对象与名字绑定（转贴，此文甚好）</a>
				</h2>
				<font face="Courier" color="#0066ff">i = 1</font>
				<p>  这是一个再简单不过的赋值语句，即便是才开始学习编程的新手也能脱口而出它的含义 -- “设置变量i的值为1”。</p>
				<p>
						<font face="Courier New" color="#0066ff">i = 2</font>
				</p>
				<p>  “将变量i的值改为2”，当看到接下来这行代码时，你脑海中肯定会立即浮现这样的念头。</p>
				<p>  这难道会有问题嘛？这简简单单的一行赋值语句其实包含了python中的三个重要概念：名字、绑定和对象。<br />python对赋值语句作出了自己的定义：<br />  “符值语句是用来将名字绑定（或重新绑定）到某个对象的操作，而且它也可用来修改可变对象的属性或<br />对象中所包含的成员。”</p>
				<p>  名字绑定到对象这个概念在python中随处可见，可以说是python的最基本而且最重要的概念之一。如果<br />没有很好理解这一点，一些意想不到的结果就会在您的代码中悄然出现。</p>
				<p>  先来看一个简单例子：</p>
				<p>
						<font face="Courier New" color="#0066ff">&gt;&gt;&gt; a = {'g':1}<br />&gt;&gt;&gt; b = a*4<br />&gt;&gt;&gt; print b<br />[{'g': 1}, {'g': 1}, {'g': 1}, {'g': 1}]<br />&gt;&gt;&gt; b[0]['g'] = 2<br />&gt;&gt;&gt; print b</font>
				</p>
				<p>  出乎意料嘛？请慢慢看完这篇文章。</p>
				<p>1. 对象<br />  “万物皆对象”(Everything is object)，这是python这种面向对象语言所倡导的理念。在我们熟悉的C++中，1只是一个整型数，而不是一个对象。但在python中，1却是一个实实在在的对象，您可以用dir(1)来显示它的属性。</p>
				<p>  在python中，所有对象都有下面三个特征：<br /> * 唯一的标识码(identity)<br /> * 类型<br /> * 内容（或称为值）</p>
				<p>  一旦对象被创建，它的标识码就不允许更改。对象的标识码可以有内建函数id()获取，它是一个整型数。您可以将它想象为该对象在内存中的地址，其实在目前的实现中标识码也就是该对象的内存地址。</p>
				<p>
						<font face="Courier New" color="#0066ff">&gt;&gt;&gt; class c1:<br /> pass<br />...<br />&gt;&gt;&gt; obj = c1()<br />&gt;&gt;&gt; obj<br />&lt;__main__.c1 instance at 0x00AC0738&gt;<br />&gt;&gt;&gt; id(obj)<br />11274040</font>
				</p>
				<p>  换算一下，11274040就是十六进制的0x00AC0738。</p>
				<p>
						<font face="Courier New" color="#0066ff">&gt;&gt;&gt; id(1)<br />7957136</font>
				</p>
				<p>
						<font color="#ff0000">  这就是前面提到的1这个对象的标识码，也就是它在内存中的地址。</font>
				</p>
				<p>
						<font color="#ff0000">  当用is操作符比较两个对象时，就是在比较它们的标识码。更确切地说，is操作符是在判断两个对象是否是同一个对象。<br /><font face="Courier New">&gt;&gt;&gt; [1] is [1]</font><br />  其结果是False，是因为这是两个不同的对象，存储在内存中的不同地方。</font>
				</p>
				<p>
						<font color="#ff0000">
								<font face="Courier New">&gt;&gt;&gt; [1] == [1]</font>
								<br />  其结果是True，是因为这两个不同的对象有着相同的值。</font>
				</p>
				<p>  与对象的标识码类似，对象的类型也是不可更改的。可以用内建函数type()取得对象的类型。</p>
				<p>  有的对象的值是可以改变的，这类对象叫作可变对象；而另外一些对象在创建后其值是不可改变的（如1这个对象），这类对象叫作恒定对象。对象的可变性是由它的类型决定的，比如数值型(number)、字符串型(string)以及序列型(tuple)的对象是恒定对象；而字典型(dictionary)和列表型(list)的对象是可变对象。</p>
				<p>  除了上面提到的三个特征外，一个对象可能：<br /> * 没有或者拥有多个方法<br /> * 没有或者有多个名字</p>
				<p>2. 名字<br />  名字是对一个对象的称呼，一个对象可以只有一个名字，也可以没有名字或取多个名字。但对象自己却不知道有多少名字，叫什么，只有名字本身知道它所指向的是个什么对象。给对象取一个名字的操作叫作命名，python将赋值语句认为是一个命名操作（或者称为名字绑定）。</p>
				<p>  名字在一定的名字空间内有效，而且唯一，不可能在同一个名字空间内有两个或更多的对象取同一名字。</p>
				<p>  让我们再来看看本篇的第一个例子：i = 1。在python中，它有如下两个含义：<br /> * 创建一个值为1的整型对象<br /> * "i"是指向该整型对象的名字（而且它是一个引用）<br /> <br />3. 绑定<br />  如上所讲的，绑定就是将一个对象与一个名字联系起来。更确切地讲，就是增加该对象的引用计数。众所周知，C++中一大问题就是内存泄漏 -- 即动态分配的内存没有能够回收，而解决这一问题的利器之一就是引用计数。python就采用了这一技术实现其垃圾回收机制。<br />  <br />  python中的所有对象都有引用计数。</p>
				<p>
						<font face="Courier New" color="#0066ff">i=i+1</font>
				</p>
				<p>* 这创建了一个新的对象，其值为i+1。<br />* "i"这个名字指向了该新建的对象，该对象的引用计数加一，而"i"以前所指向的老对象的<br />  引用计数减一。<br />* "i"所指向的老对象的值并没有改变。<br />* 这就是为什么在python中没有++、--这样的单目运算符的一个原因。</p>
				<p>3.1 引用计数<br />  对象的引用计数在下列情况下会增加：<br /> * 赋值操作<br /> * 在一个容器（列表，序列，字典等等）中包含该对象</p>
				<p>  对象的引用计数在下列情况下会减少：<br /> * 离开了当前的名字空间（该名字空间中的本地名字都会被销毁）<br /> * 对象的一个名字被绑定到另外一个对象<br /> * 对象从包含它的容器中移除<br /> * 名字被显示地用del销毁（如：del i）</p>
				<p>  当对象的引用计数降到0后，该对象就会被销毁，其所占的内存也就得以回收。</p>
				<p>4. 名字绑定所带来的一些奇特现象</p>
				<p>例4.1：<br /><font face="Courier New" color="#0066ff">&gt;&gt;&gt; li1 = [7, 8, 9, 10]<br />&gt;&gt;&gt; li2 = li1<br />&gt;&gt;&gt; li1[1] = 16<br />&gt;&gt;&gt; print li2<br />[7, 16, 9, 10]</font></p>
				<p>注解：这里li1与li2都指向同一个列表对象[7, 8, 9, 10]，“li[1] = 16”是改变该列表中的第2个元素，所以通过li2时同样会看到这一改动。</p>
				<p>例4.2：<br /><font face="Courier New" color="#ff0000">&gt;&gt;&gt; b = [{'g':1}]*4<br />&gt;&gt;&gt; print b<br />[{'g': 1}, {'g': 1}, {'g': 1}, {'g': 1}]<br />&gt;&gt;&gt; b[0]['g'] = 2<br />&gt;&gt;&gt; print b<br />[{'g': 2}, {'g': 2}, {'g': 2}, {'g': 2}]</font></p>
				<p>
						<font color="#ff0000">例4.3：<br /></font>
						<font face="Courier New" color="#ff0000">&gt;&gt;&gt; b = [{'g':1}] + [{'g':1}] + [{'g':1}] + [{'g':1}]<br />&gt;&gt;&gt; print b<br />[{'g': 1}, {'g': 1}, {'g': 1}, {'g': 1}]<br />&gt;&gt;&gt; b[0]['g'] = 2<br />&gt;&gt;&gt; print b<br />[{'g': 2}, {'g': 1}, {'g': 1}, {'g': 1}]</font>
				</p>
				<p>
						<font color="#ff0000">注解：在有的python书中讲到乘法符号（*）就相当于几个加法的重复，即认为例4.2应该与4.3的结果一致。<br />      其实不然。例4.2中的b这个列表中的每一个元素{'g': 1}其实都是同一个对象，可以用id(b[n])进行验证。而例4.3中则是四个不同的对象。我们可以采用名字绑定的方法消除这一歧义：</font>
				</p>
				<p>
						<font face="Courier New" color="#0066ff">&gt;&gt;&gt; a = {'g' : 1}<br />&gt;&gt;&gt; b = [a]*4<br />&gt;&gt;&gt; b[0]['g'] = 2<br />&gt;&gt;&gt; print b<br />[{'g': 2}, {'g': 2}, {'g': 2}, {'g': 2}]<br />&gt;&gt;&gt; print a<br />{'g': 2}</font>
				</p>
				<p>
						<font face="Courier New" color="#0066ff">&gt;&gt;&gt; a = {'g' : 1}<br />&gt;&gt;&gt; b = [a] + [a] + [a] + [a]<br />&gt;&gt;&gt; b[0]['g'] = 2<br />&gt;&gt;&gt; print b<br />[{'g': 2}, {'g': 2}, {'g': 2}, {'g': 2}]<br />&gt;&gt;&gt; print a<br />{'g': 2}</font>
				</p>
				<p>  不过对于恒定对象而言，“*”和连续加法的效果一样。比如，b=[1] * 4 就等同于 b=[1]+[1]+[1]+[1]。</p>
				<p>5. 函数的传参问题<br />  函数的参数传递也是一个名字与对象的绑定过程，而且是绑定到另外一个名字空间（即函数体内部的名字空间）。python对赋值语句的独特看法又会对函数的传递造成什么影响呢？</p>
				<p>5.1 传值？传址？<br />  在学习C++的时候我们都知道有两种参数传递方式：传值和传址。而在python中所有的参数传递都是引用传递（pass reference），也就是传址。这是由于名字是对象的一个引用这一python的特性而自然得来的，在函数体内部对某一外部可变对象作了修改肯定会将其改变带到函数以外。让我们来看看下面<br />这个例子：</p>
				<p>例5.1<br /><font face="Courier New" color="#0066ff">&gt;&gt;&gt; a = [1, 2, 3]<br />&gt;&gt;&gt; def foo(par):<br />... par[1] = 10<br />...<br />&gt;&gt;&gt; foo(a)<br />&gt;&gt;&gt; print a<br />[1, 10, 3]</font></p>
				<p>  因此，在python中，我们应该抛开传递参数这种概念，时刻牢记函数的调用参数是将对象用另外一个名字空间的名字绑定。在函数中，不过是用了另外一个名字，但还是对这同一个对象进行操作。</p>
				<p>5.2 缺省参数<br />  使用缺省参数，是我们喜爱的一种作法。这可以在调用该函数时节省不少的击键次数，而且代码也显得更加简洁。更重要的是它从某种意义上体现了这个函数设计的初衷。<br />  但是python中的缺省参数，却隐藏着一个玄机，初学者肯定会在上面栽跟头，而且这个错误非常隐秘。先看看下面这个例子：</p>
				<p>例5.2<br /><font face="Courier New" color="#0066ff">&gt;&gt;&gt; def foo(par=[]):<br />... par.append(0)<br />... print par<br />... <br />&gt;&gt;&gt; foo()                       # 第一次调用<br />[0]<br />&gt;&gt;&gt; foo()                       # 第二次调用<br />[0, 0]</font></p>
				<p>  出了什么问题？这个参数par好像类似与C中的静态变量，累计了以前的结果。是这样吗？当然不是，这都是“对象、名字、绑定”这些思想惹的“祸”。“万物皆对象”，还记得吗？这里，函数foo当然也是一个对象，可以称之为函数对象（与一般的对象没什么不同）。先来看看这个对象有些什么属性。</p>
				<p>
						<font face="Courier New" color="#0066ff">&gt;&gt;&gt; dir(foo)<br />['__call__', '__class__', '__delattr__', '__dict__', '__doc__', '__get__', '__getattribute__', '__hash__', '__init__', '__module__', '__name__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__str__', 'func_closure', 'func_code', 'func_defaults', 'func_dict', 'func_doc', 'func_globals', 'func_name']</font>
				</p>
				<p>  单从名字上看，“func_defaults”很可能与缺省参数有关，看看它的值。</p>
				<p>
						<font face="Courier New" color="#0066ff">&gt;&gt;&gt; foo.func_defaults          # 显示这个属性的内容<br />([0, 0],)<br />&gt;&gt;&gt; foo()                      # 第三次调用<br />[0, 0, 0]<br />&gt;&gt;&gt; foo.func_defaults          # 再来看看这个属性<br />([0, 0, 0],)</font>
				</p>
				<p>  果不其然，就是这个序列对象（tuple)包含了所有的缺省参数。验证一下：</p>
				<p>
						<font face="Courier New" color="#0066ff">&gt;&gt;&gt; def fooM(par1, def1=1, def2=[], def3='str'):           # 定义一个有多个缺省参数的函数<br />... def2.append(0)<br />... print par1, def1, def2, def3<br />...<br />&gt;&gt;&gt; fooM.func_defaults<br />(1, [], 'str')</font>
				</p>
				<p>  在函数定义中有几个缺省参数，func_defaults中就会包括几个对象，暂且称之为缺省参数对象（如上列中的1，[]和'str'）。这些缺省参数对象的生命周期与函数对象相同，从函数使用def定义开始，直到其消亡（如用del）。所以即便是在这些函数没有被调用的时候，但只要定义了，缺省参数对象就会一直存在。</p>
				<p>  前面讲过，函数调用的过程就是对象在另外一个名字空间的绑定过程。当在每次函数调用时，如果没有传递任何参数给这个缺省参数，那么这个缺省参数的名字就会绑定到在func_defaults中一个对应的缺省参数对象上。<br /><font face="Courier New" color="#0066ff">&gt;&gt;&gt; fooM(2)<br /></font>  函数fooM内的名字def1就会绑定到func_defaults中的第一个对象，def2绑定到第二个，def3则是第三个。<br />所以我们看到在函数foo中出现的累加现象，就是由于par绑定到缺省参数对象上，而且它是一个可变对象（列表），par.append(0)就会每次改变这个缺省参数对象的内容。</p>
				<p>  将函数foo改进一下，可能会更容易帮助理解：<br /><font face="Courier New" color="#0066ff">&gt;&gt;&gt; def foo(par=[]):<br />... print id(par)                  # 查看该对象的标识码<br />... par.append(0)<br />... print par<br />...<br />&gt;&gt;&gt; foo.func_defaults                  # 缺省参数对象的初始值<br />([],)<br />&gt;&gt;&gt; id(foo.func_defaults[0])           # 查看第一个缺省参数对象的标识码<br />11279792                               # 你的结果可能会不同<br />&gt;&gt;&gt; foo()                                <br />11279792                               # 证明par绑定的对象就是第一个缺省参数对象<br />[0]<br />&gt;&gt;&gt; foo()<br />11279792                               # 依旧绑定到第一个缺省参数对象<br />[0, 0]                                 # 该对象的值发生了变化<br />&gt;&gt;&gt; b=[1]<br />&gt;&gt;&gt; id(b)<br />11279952<br />&gt;&gt;&gt; foo(b)                             # 不使用缺省参数<br />11279952                               # 名字par所绑定的对象与外部名字b所绑定的是同一个对象<br />[1, 0]<br />&gt;&gt;&gt; foo.func_defaults<br />([0, 0],)                              # 缺省参数对象还在那里，而且值并没有发生变化<br />&gt;&gt;&gt; foo()                    <br />11279792                               # 名字par又绑定到缺省参数对象上<br />([0, 0, 0],)</font></p>
				<p>  为了预防此类“问题”的发生，python建议采用下列方法：<br /><font face="Courier New" color="#0066ff">&gt;&gt;&gt; def foo(par=[]):<br />... if par is None:<br />...  par = []<br />... par.append(0)<br />... print par</font></p>
				<p>  使用None作为哨兵，以判断是否有参数传入，如果没有，就新创建一个新的列表对象，而不是绑定到缺省<br />参数对象上。</p>
				<p>6.总结<br />  * python是一种纯粹的面向对象语言。<br />  * 赋值语句是名字和对象的绑定过程。<br />  * 函数的传参是对象到不同名字空间的绑定。</p>
				<p>7.参考资料<br />  * 《Dive Into Python》，Mark Pilgrim，<a href="http://diveintopython.org/"><font color="#000000">http://diveintopython.org</font></a>, 2003。<br />  * 《Python Objects》，Fredrik Lundh，<a href="http://www.effbot.org/zone/python-objects.htm"><font color="#000000">http://www.effbot.org/zone/python-objects.htm</font></a>。<br />  * 《An Introduction to Python》，David M. Beazley，<a href="http://systems.cs.uchicago.edu/~beazley/tutorial/beazley_intro_python/intropy.pdf"><font color="#000000">http://systems.cs.uchicago.edu/~beazley/tutorial/beazley_intro_python/intropy.pdf</font></a>。<br />  *  从Python官方网站（<a href="http://www.python.org/"><font color="#000000">http://www.python.org</font></a>）上可以了解到所有关于Python的知识。<br /></p>
				<p class="postfoot">posted on 2005-06-25 10:41 <a href="http://sirsunny.cnblogs.com/">I love linux</a> 阅读(670) <a href="http://sirsunny.cnblogs.com/archive/2005/06/25/180898.html#Post">评论(2)</a>  <a href="http://sirsunny.cnblogs.com/admin/EditPosts.aspx?postid=180898">编辑</a> <a href="http://sirsunny.cnblogs.com/AddToFavorite.aspx?id=180898">收藏</a><a title="功能强大的网络收藏夹，一秒钟操作就可以轻松实现保存带来的价值、分享带来的快乐" href="javascript:d=document;t=d.selection?(d.selection.type!='None'?d.selection.createRange().text:''):(d.getSelection?d.getSelection():'');void(keyit=window.open('http://www.365key.com/storeit.aspx?t='+escape(d.title)+'&amp;u='+escape(d.location.href)+'&amp;c='+escape(t),'keyit','scrollbars=no,width=475,height=575,left=75,top=20,status=no,resizable=yes'));keyit.focus();">收藏至365Key</a> 所属分类: <a href="http://sirsunny.cnblogs.com/category/8673.html">Python</a></p>
		</div>
		<img height="1" src="http://sirsunny.cnblogs.com/aggbug/180898.html?webview=1" width="1" />
		<!--
<rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
xmlns:dc="http://purl.org/dc/elements/1.1/"
xmlns:trackback="http://madskills.com/public/xml/rss/module/trackback/">
<rdf:Description
rdf:about="http://sirsunny.cnblogs.com/archive/2005/06/25/180898.html"
dc:identifier="http://sirsunny.cnblogs.com/archive/2005/06/25/180898.html"
dc:title="python的对象与名字绑定（转贴，此文甚好）"
trackback:ping="http://sirsunny.cnblogs.com/services/trackbacks/180898.aspx" />
</rdf:RDF>
-->
		<a name="评论">
				<div id="comments">
						<h3>评论</h3>
						<h4>
								<a title="permalink: re: python的对象与名字绑定（转贴，此文甚好）" href="http://sirsunny.cnblogs.com/archive/2005/06/25/180898.html#306728">#</a> <a name="306728"></a>re: python的对象与名字绑定（转贴，此文甚好） <span>2005-12-28 16:43 </span><a id="Comments1_CommentList_ctl00_NameLink" target="_blank">jarodzz</a></h4>
						<p>因此，在python中，我们应该抛开传递参数这种概念，时刻牢记函数的调用参数是将对象用另外一个名字空间的名字绑定。在函数中，不过是用了另外一个名字，但还是对这同一个对象进行操作。 <br /><br />def foolyou(a): <br />a=a+1 <br /><br />if __name__=='__main__': <br />b=1 <br />foolyou(b) <br />print b <br /><br />what is b now?  <a onclick="return SetReplyAuhor(&quot;jarodzz&quot;)" href="http://sirsunny.cnblogs.com/archive/2005/06/25/180898.html#post">回复</a><a id="Comments1_CommentList_ctl00_DeleteLink" href="javascript:__doPostBack('Comments1$CommentList$ctl00$DeleteLink','')"></a>  <a id="Comments1_CommentList_ctl00_EditLink"></a></p>
						<h4>
								<a title="permalink: re: python的对象与名字绑定（转贴，此文甚好）" href="http://sirsunny.cnblogs.com/archive/2005/06/25/180898.html#310845">#</a> <a name="310845"></a>re: python的对象与名字绑定（转贴，此文甚好）<a name="Post"></a><span>2006-01-04 16:15 </span><a id="Comments1_CommentList_ctl01_NameLink" target="_blank">asdf_asdf</a></h4>
						<p>a=a+1 已经是另一个"引用"了 <br />&gt;&gt;&gt; def foolyou(a): <br />print id(a) <br />a=a+1 <br />print id(a) <br /><br />&gt;&gt;&gt; b <br />1 <br />&gt;&gt;&gt; foolyou(b) <br />148479408 <br />148479396 <br />&gt;&gt;&gt; id(b) <br />148479408  <a onclick="return SetReplyAuhor(&quot;asdf_asdf&quot;)" href="http://sirsunny.cnblogs.com/archive/2005/06/25/180898.html#post">回复</a><a id="Comments1_CommentList_ctl01_DeleteLink" href="javascript:__doPostBack('Comments1$CommentList$ctl01$DeleteLink','')"></a>  <a id="Comments1_CommentList_ctl01_EditLink"></a></p>
				</div>
				<style><![CDATA[
TD { FONT-SIZE: 12px }
.commentTextBox { FONT-SIZE: 12px }
]]&gt;</style>
				<!--Beging Temp Save-->
				<style><![CDATA[userData { BEHAVIOR: url(#default#userdata) }
	]]&gt;</style>
		</a>
<img src ="http://www.cppblog.com/Jeff-Chen/aggbug/5785.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.cppblog.com/Jeff-Chen/" target="_blank">Jeff-Chen</a> 2006-04-17 19:27 <a href="http://www.cppblog.com/Jeff-Chen/archive/2006/04/17/5785.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item><item><title>The most classical topic for Python novices</title><link>http://www.cppblog.com/Jeff-Chen/archive/2006/04/16/5651.html</link><dc:creator>Jeff-Chen</dc:creator><author>Jeff-Chen</author><pubDate>Sun, 16 Apr 2006 08:58:00 GMT</pubDate><guid>http://www.cppblog.com/Jeff-Chen/archive/2006/04/16/5651.html</guid><wfw:comment>http://www.cppblog.com/Jeff-Chen/comments/5651.html</wfw:comment><comments>http://www.cppblog.com/Jeff-Chen/archive/2006/04/16/5651.html#Feedback</comments><slash:comments>0</slash:comments><wfw:commentRss>http://www.cppblog.com/Jeff-Chen/comments/commentRss/5651.html</wfw:commentRss><trackback:ping>http://www.cppblog.com/Jeff-Chen/services/trackbacks/5651.html</trackback:ping><description><![CDATA[&nbsp;&nbsp;&nbsp;&nbsp; 摘要: Python 101 -- Introduction to Python																																																																										Python 101 -- Introduction to Python																						...&nbsp;&nbsp;<a href='http://www.cppblog.com/Jeff-Chen/archive/2006/04/16/5651.html'>阅读全文</a><img src ="http://www.cppblog.com/Jeff-Chen/aggbug/5651.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.cppblog.com/Jeff-Chen/" target="_blank">Jeff-Chen</a> 2006-04-16 16:58 <a href="http://www.cppblog.com/Jeff-Chen/archive/2006/04/16/5651.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item><item><title>Python 学习之路（提高总结）</title><link>http://www.cppblog.com/Jeff-Chen/archive/2006/04/15/5611.html</link><dc:creator>Jeff-Chen</dc:creator><author>Jeff-Chen</author><pubDate>Sat, 15 Apr 2006 05:13:00 GMT</pubDate><guid>http://www.cppblog.com/Jeff-Chen/archive/2006/04/15/5611.html</guid><wfw:comment>http://www.cppblog.com/Jeff-Chen/comments/5611.html</wfw:comment><comments>http://www.cppblog.com/Jeff-Chen/archive/2006/04/15/5611.html#Feedback</comments><slash:comments>0</slash:comments><wfw:commentRss>http://www.cppblog.com/Jeff-Chen/comments/commentRss/5611.html</wfw:commentRss><trackback:ping>http://www.cppblog.com/Jeff-Chen/services/trackbacks/5611.html</trackback:ping><description><![CDATA[
		<strong>Note One ： Lists Comprehensions<br /></strong>[3*x for x in vec if x &gt; 3]<br />[x*y for x in vec1 for y in vec2]<br />......<br />there expression can used to instead the functional programming tools such as map() ,filter(),reduce()..<br /><br /><strong>Note Two : Some functions in the modules often  be made used of<br />1.strip()</strong> :  Return a copy of the string s with leading and trailing whitespace removed.<br />&gt;&gt;&gt; test_str = '   I Love Python  '<br />&gt;&gt;&gt; string.strip(test_str)<br />'I Love Pyhon'    Note that : whitespace at the two side of the string were removed ,but it did not worked on the whitespace between string!<br /><strong>2. str()</strong> : can convert the format like int ,long , float ... into string format<br />&gt;&gt;&gt; num_1 = 3.14<br />&gt;&gt;&gt; num_2 = 0.618<br />&gt;&gt;&gt; str(num_1) , str(num_2)<br />'3.14' '0.618'<br /><strong>3.dict()</strong><br />dict() -&gt; new empty dictionary.<br />dict(mapping) -&gt; new dictionary initialized from a mapping object's<br />    (key, value) pairs.<br />dict(seq) -&gt; new dictionary initialized as if via:<br />    d = {}<br />    for k, v in seq:<br />        d[k] = v<br />dict(**kwargs) -&gt; new dictionary initialized with the name=value pairs<br />    in the keyword argument list.  For example:  dict(one=1, two=2)<br /><br />e.g  <br />dict([('sape', 4139), ('guido', 4127), ('jack', 4098)])<br />dict([(x, x**2) for x in (2, 4, 6)])     <br />dict(sape=4139, guido=4127, jack=4098)<br /><br /><strong>4. enumerate()</strong><br />Return an enumerate object.  iterable must be an other object that supports<br />iteration.  The enumerate object yields pairs containing a count (from<br />zero) and a value yielded by the iterable argument.  enumerate is useful<br />for obtaining an indexed list: (0, seq[0]), (1, seq[1]), (2, seq[2]), ...<br />Code  show:<br />&gt;&gt;&gt; for i, v in enumerate(['tic', 'tac', 'toe']):<br />...     print i, v<br />...<br />0 tic<br />1 tac<br />2 toe<br /><br /><strong>5 zip()<br /></strong>Return an enumerate object.  iterable must be an other object that supports<br />iteration.  The enumerate object yields pairs containing a count (from<br />zero) and a value yielded by the iterable argument.  enumerate is useful<br />for obtaining an indexed list: (0, seq[0]), (1, seq[1]), (2, seq[2]), ...<br />Code Show:<br /><br /><pre>&gt;&gt;&gt; questions = ['name', 'quest', 'favorite color']
&gt;&gt;&gt; answers = ['lancelot', 'the holy grail', 'blue']
&gt;&gt;&gt; for q, a in zip(questions, answers):
...     print 'What is your %s?  It is %s.' % (q, a)
...	
What is your name?  It is lancelot.
What is your quest?  It is the holy grail.
What is your favorite color?  It is blue.
</pre><br /><strong>6.sorted()<br /></strong>Code Show:<br /><pre>&gt;&gt;&gt; basket = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana']
&gt;&gt;&gt; for f in sorted(set(basket)):
...     print f
... 	
apple
banana
orange
pear
</pre><br />to be continued......<br /><br /><strong>Note Three : simple statements</strong><br /><br /><strong>7 The <tt class="keyword">yield</tt> statement</strong><br /><dl><dd class="grammar"><div class="productions"><table><tbody><tr><td><a id="tok-yield_stmt" xml:id="tok-yield_stmt">yield_stmt</a></td><td>::=</td><td>"yield" <a class="grammartoken" href="mk:@MSITStore:D:\Document\E-Book\Python24.chm::/ref/exprlists.html#tok-expression_list"><font color="#002c99">expression_list</font></a></td></tr></tbody></table></div><a class="grammar-footer" href="mk:@MSITStore:D:\Document\E-Book\Python24.chm::/ref/grammar.txt" type="text/plain"><font color="#002c99">Download entire grammar as text.</font></a></dd></dl><p><a id="l2h-512" xml:id="l2h-512"></a><a id="l2h-511" xml:id="l2h-511"></a></p><p>The <tt class="keyword">yield</tt> statement is only used when defining a generator function, and is only used in the body of the generator function. Using a <tt class="keyword">yield</tt> statement in a function definition is sufficient to cause that definition to create a generator function instead of a normal function. 
</p><p>When a generator function is called, it returns an iterator known as a generator iterator, or more commonly, a generator. The body of the generator function is executed by calling the generator's <tt class="method">next()</tt> method repeatedly until it raises an exception. 
</p><p>When a <tt class="keyword">yield</tt> statement is executed, the state of the generator is frozen and the value of <a class="grammartoken" href="mk:@MSITStore:D:\Document\E-Book\Python24.chm::/ref/exprlists.html#tok-expression_list"><font color="#002c99">expression_list</font></a> is returned to <tt class="method">next()</tt>'s caller. By ``frozen'' we mean that all local state is retained, including the current bindings of local variables, the instruction pointer, and the internal evaluation stack: enough information is saved so that the next time <tt class="method">next()</tt> is invoked, the function can proceed exactly as if the <tt class="keyword">yield</tt> statement were just another external call. 
</p><p>The <tt class="keyword">yield</tt> statement is not allowed in the <tt class="keyword">try</tt> clause of a <tt class="keyword">try</tt> ... <tt class="keyword">finally</tt> construct. The difficulty is that there's no guarantee the generator will ever be resumed, hence no guarantee that the <tt class="keyword">finally</tt> block will ever get executed. 
</p><p></p><div class="note"><b class="label">Note:</b> In Python 2.2, the <tt class="keyword">yield</tt> statement is only allowed when the <code>generators</code> feature has been enabled. It will always be enabled in Python 2.3. This <code>__future__</code> import statement can be used to enable the feature: 
<p></p><div class="verbatim"><pre>from __future__ import generators
</pre></div></div><br /><strong>8 The <tt class="keyword">raise</tt> statement</strong><a id="l2h-513" xml:id="l2h-513"></a><p></p><dl><dd class="grammar"><div class="productions"><table><tbody><tr><td><a id="tok-raise_stmt" xml:id="tok-raise_stmt">raise_stmt</a></td><td>::=</td><td>"raise" [<a class="grammartoken" href="mk:@MSITStore:D:\Document\E-Book\Python24.chm::/ref/Booleans.html#tok-expression"><font color="#002c99">expression</font></a> ["," <a class="grammartoken" href="mk:@MSITStore:D:\Document\E-Book\Python24.chm::/ref/Booleans.html#tok-expression"><font color="#002c99">expression</font></a> ["," <a class="grammartoken" href="mk:@MSITStore:D:\Document\E-Book\Python24.chm::/ref/Booleans.html#tok-expression"><font color="#002c99">expression</font></a>]]]</td></tr></tbody></table></div><a class="grammar-footer" href="mk:@MSITStore:D:\Document\E-Book\Python24.chm::/ref/grammar.txt" type="text/plain"><font color="#002c99">Download entire grammar as text.</font></a></dd></dl><p>If no expressions are present, <tt class="keyword">raise</tt> re-raises the last exception that was active in the current scope. If no exception is active in the current scope, a <tt class="exception">TypeError</tt> exception is raised indicating that this is an error (if running under IDLE, a <tt class="exception">Queue.Empty</tt> exception is raised instead). <a id="l2h-516" xml:id="l2h-516"></a><a id="l2h-514" xml:id="l2h-514"></a></p><p>Otherwise, <tt class="keyword">raise</tt> evaluates the expressions to get three objects, using <code>None</code> as the value of omitted expressions. The first two objects are used to determine the <em>type</em> and <em>value</em> of the exception. 
</p><p>If the first object is an instance, the type of the exception is the class of the instance, the instance itself is the value, and the second object must be <code>None</code>. 
</p><p>If the first object is a class, it becomes the type of the exception. The second object is used to determine the exception value: If it is an instance of the class, the instance becomes the exception value. If the second object is a tuple, it is used as the argument list for the class constructor; if it is <code>None</code>, an empty argument list is used, and any other object is treated as a single argument to the constructor. The instance so created by calling the constructor is used as the exception value. 
</p><p>If a third object is present and not <code>None</code>, it must be a traceback<a id="l2h-515" xml:id="l2h-515"></a> object (see section <a href="mk:@MSITStore:D:\Document\E-Book\Python24.chm::/ref/types.html#traceback"><font color="#002c99">3.2</font></a>), and it is substituted instead of the current location as the place where the exception occurred. If the third object is present and not a traceback object or <code>None</code>, a <tt class="exception">TypeError</tt> exception is raised. The three-expression form of <tt class="keyword">raise</tt> is useful to re-raise an exception transparently in an except clause, but <tt class="keyword">raise</tt> with no expressions should be preferred if the exception to be re-raised was the most recently active exception in the current scope. </p><strong>Note Four : Compound Statements</strong><br /><br /><strong>9 The <tt class="keyword">try</tt> statement</strong><a id="l2h-592" xml:id="l2h-592"></a><p>The <tt class="keyword">try</tt> statement specifies exception handlers and/or cleanup code for a group of statements: 
</p><p></p><dl><dd class="grammar"><div class="productions"><table><tbody><tr><td><a id="tok-try_stmt" xml:id="tok-try_stmt">try_stmt</a></td><td>::=</td><td><a class="grammartoken" href="mk:@MSITStore:D:\Document\E-Book\Python24.chm::/ref/try.html#tok-try_exc_stmt"><font color="#002c99">try_exc_stmt</font></a> | <a class="grammartoken" href="mk:@MSITStore:D:\Document\E-Book\Python24.chm::/ref/try.html#tok-try_fin_stmt"><font color="#002c99">try_fin_stmt</font></a></td></tr><tr><td><a id="tok-try_exc_stmt" xml:id="tok-try_exc_stmt">try_exc_stmt</a></td><td>::=</td><td>"try" ":" <a class="grammartoken" href="mk:@MSITStore:D:\Document\E-Book\Python24.chm::/ref/compound.html#tok-suite"><font color="#002c99">suite</font></a></td></tr><tr><td><font color="#002c99"></font></td><td><font color="#002c99"></font></td><td><code>("except" [<a class="grammartoken" href="mk:@MSITStore:D:\Document\E-Book\Python24.chm::/ref/Booleans.html#tok-expression"><font color="#002c99">expression</font></a> ["," <a class="grammartoken" href="mk:@MSITStore:D:\Document\E-Book\Python24.chm::/ref/assignment.html#tok-target"><font color="#002c99">target</font></a>]] ":" <a class="grammartoken" href="mk:@MSITStore:D:\Document\E-Book\Python24.chm::/ref/compound.html#tok-suite"><font color="#002c99">suite</font></a>)+</code></td></tr><tr><td></td><td></td><td><code>["else" ":" <a class="grammartoken" href="mk:@MSITStore:D:\Document\E-Book\Python24.chm::/ref/compound.html#tok-suite"><font color="#002c99">suite</font></a>]</code></td></tr><tr><td><a id="tok-try_fin_stmt" xml:id="tok-try_fin_stmt">try_fin_stmt</a></td><td>::=</td><td>"try" ":" <a class="grammartoken" href="mk:@MSITStore:D:\Document\E-Book\Python24.chm::/ref/compound.html#tok-suite"><font color="#002c99">suite</font></a> "finally" ":" <a class="grammartoken" href="mk:@MSITStore:D:\Document\E-Book\Python24.chm::/ref/compound.html#tok-suite"><font color="#002c99">suite</font></a></td></tr></tbody></table></div><a class="grammar-footer" href="mk:@MSITStore:D:\Document\E-Book\Python24.chm::/ref/grammar.txt" type="text/plain"><font color="#002c99">Download entire grammar as text.</font></a></dd></dl><p>There are two forms of <tt class="keyword">try</tt> statement: <tt class="keyword">try</tt>...<tt class="keyword">except</tt> and <tt class="keyword">try</tt>...<tt class="keyword">finally</tt>. These forms cannot be mixed (but they can be nested in each other). 
</p><p>The <tt class="keyword">try</tt>...<tt class="keyword">except</tt> form specifies one or more exception handlers (the <tt class="keyword">except</tt> clauses). When no exception occurs in the <tt class="keyword">try</tt> clause, no exception handler is executed. When an exception occurs in the <tt class="keyword">try</tt> suite, a search for an exception handler is started. This search inspects the except clauses in turn until one is found that matches the exception. An expression-less except clause, if present, must be last; it matches any exception. For an except clause with an expression, that expression is evaluated, and the clause matches the exception if the resulting object is ``compatible'' with the exception. An object is compatible with an exception if it is either the object that identifies the exception, or (for exceptions that are classes) it is a base class of the exception, or it is a tuple containing an item that is compatible with the exception. Note that the object identities must match, i.e. it must be the same object, not just an object with the same value. <a id="l2h-593" xml:id="l2h-593"></a></p><p>If no except clause matches the exception, the search for an exception handler continues in the surrounding code and on the invocation stack. 
</p><p>If the evaluation of an expression in the header of an except clause raises an exception, the original search for a handler is canceled and a search starts for the new exception in the surrounding code and on the call stack (it is treated as if the entire <tt class="keyword">try</tt> statement raised the exception). 
</p><p>When a matching except clause is found, the exception's parameter is assigned to the target specified in that except clause, if present, and the except clause's suite is executed. All except clauses must have an executable block. When the end of this block is reached, execution continues normally after the entire try statement. (This means that if two nested handlers exist for the same exception, and the exception occurs in the try clause of the inner handler, the outer handler will not handle the exception.) 
</p><p>Before an except clause's suite is executed, details about the exception are assigned to three variables in the <tt class="module">sys</tt><a id="l2h-605" xml:id="l2h-605"></a> module: <code>sys.exc_type</code> receives the object identifying the exception; <code>sys.exc_value</code> receives the exception's parameter; <code>sys.exc_traceback</code> receives a traceback object<a id="l2h-594" xml:id="l2h-594"></a> (see section <a href="mk:@MSITStore:D:\Document\E-Book\Python24.chm::/ref/types.html#traceback"><font color="#002c99">3.2</font></a>) identifying the point in the program where the exception occurred. These details are also available through the <tt class="function">sys.exc_info()</tt> function, which returns a tuple <code>(<var>exc_type</var>, <var>exc_value</var>, <var>exc_traceback</var>)</code>. Use of the corresponding variables is deprecated in favor of this function, since their use is unsafe in a threaded program. As of Python 1.5, the variables are restored to their previous values (before the call) when returning from a function that handled an exception. <a id="l2h-596" xml:id="l2h-596"></a></p><p>The optional <tt class="keyword">else</tt> clause is executed if and when control flows off the end of the <tt class="keyword">try</tt> clause.<a href="mk:@MSITStore:D:\Document\E-Book\Python24.chm::/ref/try.html#foot6714" name="tex2html10"><sup><font color="#002c99">7.1</font></sup></a> Exceptions in the <tt class="keyword">else</tt> clause are not handled by the preceding <tt class="keyword">except</tt> clauses. <a id="l2h-597" xml:id="l2h-597"></a><a id="l2h-598" xml:id="l2h-598"></a><a id="l2h-599" xml:id="l2h-599"></a><a id="l2h-600" xml:id="l2h-600"></a></p><p>The <tt class="keyword">try</tt>...<tt class="keyword">finally</tt> form specifies a `cleanup' handler. The <tt class="keyword">try</tt> clause is executed. When no exception occurs, the <tt class="keyword">finally</tt> clause is executed. When an exception occurs in the <tt class="keyword">try</tt> clause, the exception is temporarily saved, the <tt class="keyword">finally</tt> clause is executed, and then the saved exception is re-raised. If the <tt class="keyword">finally</tt> clause raises another exception or executes a <tt class="keyword">return</tt> or <tt class="keyword">break</tt> statement, the saved exception is lost. A <tt class="keyword">continue</tt> statement is illegal in the <tt class="keyword">finally</tt> clause. (The reason is a problem with the current implementation - this restriction may be lifted in the future). The exception information is not available to the program during execution of the <tt class="keyword">finally</tt> clause. <a id="l2h-601" xml:id="l2h-601"></a></p><p>When a <tt class="keyword">return</tt>, <tt class="keyword">break</tt> or <tt class="keyword">continue</tt> statement is executed in the <tt class="keyword">try</tt> suite of a <tt class="keyword">try</tt>...<tt class="keyword">finally</tt> statement, the <tt class="keyword">finally</tt> clause is also executed `on the way out.' A <tt class="keyword">continue</tt> statement is illegal in the <tt class="keyword">finally</tt> clause. (The reason is a problem with the current implementation -- this restriction may be lifted in the future). <br /></p><img src ="http://www.cppblog.com/Jeff-Chen/aggbug/5611.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.cppblog.com/Jeff-Chen/" target="_blank">Jeff-Chen</a> 2006-04-15 13:13 <a href="http://www.cppblog.com/Jeff-Chen/archive/2006/04/15/5611.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item><item><title>Serious Recommend:Python Documentation Tips and Tricks</title><link>http://www.cppblog.com/Jeff-Chen/archive/2006/04/14/5535.html</link><dc:creator>Jeff-Chen</dc:creator><author>Jeff-Chen</author><pubDate>Fri, 14 Apr 2006 05:27:00 GMT</pubDate><guid>http://www.cppblog.com/Jeff-Chen/archive/2006/04/14/5535.html</guid><wfw:comment>http://www.cppblog.com/Jeff-Chen/comments/5535.html</wfw:comment><comments>http://www.cppblog.com/Jeff-Chen/archive/2006/04/14/5535.html#Feedback</comments><slash:comments>0</slash:comments><wfw:commentRss>http://www.cppblog.com/Jeff-Chen/comments/commentRss/5535.html</wfw:commentRss><trackback:ping>http://www.cppblog.com/Jeff-Chen/services/trackbacks/5535.html</trackback:ping><description><![CDATA[Error convertoring HTML to XHTML: System.ArgumentException: Cannot have ']]&gt;' inside an XML CDATA block.
   at System.Xml.XmlTextWriter.WriteCData(String text)
   at System.Xml.XmlWriter.WriteNode(XmlReader reader, Boolean defattr)
   at FreeTextBoxControls.Support.Formatter.HtmlToXhtml(String input)<img src ="http://www.cppblog.com/Jeff-Chen/aggbug/5535.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.cppblog.com/Jeff-Chen/" target="_blank">Jeff-Chen</a> 2006-04-14 13:27 <a href="http://www.cppblog.com/Jeff-Chen/archive/2006/04/14/5535.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item><item><title>无法在eclipse中更新pydev（供遇到此类问题的朋友参考）</title><link>http://www.cppblog.com/Jeff-Chen/archive/2006/04/14/5525.html</link><dc:creator>Jeff-Chen</dc:creator><author>Jeff-Chen</author><pubDate>Fri, 14 Apr 2006 04:00:00 GMT</pubDate><guid>http://www.cppblog.com/Jeff-Chen/archive/2006/04/14/5525.html</guid><wfw:comment>http://www.cppblog.com/Jeff-Chen/comments/5525.html</wfw:comment><comments>http://www.cppblog.com/Jeff-Chen/archive/2006/04/14/5525.html#Feedback</comments><slash:comments>0</slash:comments><wfw:commentRss>http://www.cppblog.com/Jeff-Chen/comments/commentRss/5525.html</wfw:commentRss><trackback:ping>http://www.cppblog.com/Jeff-Chen/services/trackbacks/5525.html</trackback:ping><description><![CDATA[
		<table cellspacing="0" cellpadding="0" width="100%" border="0">
				<tbody>
						<tr valign="top">
								<td>
										<span class="atitle">头疼了很久,eclipse中无法正常更新pydev。我又回头检查，域名是正确的，但是还是出现错误。<br />想了很久，在网上到处找关于此类问题的文章，但是收获不大，可以说几乎找不到之类文章。<br />幸运的事 ，我正在寻找其他插件时候和察看其他python开发工具的时候，无意中点出了IBM 的下面这个页面。<br />顿时我就恍然大悟，才发现无法更新的原因：<br />因为公司的封掉了几个端口，防止使用非工作范围内的娱乐软件或其他的聊天软件，<br />而eclipse的更新模式基于基于FTP模式的。<br />当然这是造成无法更新的原因之一，可能还有其他原因但是我没想到，也没遇见过。<br /><br />quote:<br /><br />下载方法：FTP、HTTP 和下载助手</span>
								</td>
								<td width="8">
										<img height="1" alt="" src="http://www.ibm.com/i/c.gif" width="8" border="0" />
								</td>
								<td align="right" width="180">
										<img height="1" alt="" src="http://www.ibm.com/i/c.gif" width="180" border="0" />
										<br />
										<nobr>
										</nobr>
								</td>
								<td width="6">
										<img height="1" alt="" src="http://www.ibm.com/i/c.gif" width="6" border="0" />
								</td>
						</tr>
						<tr valign="top">
								<td bgcolor="#000000" colspan="5">
										<img height="1" alt="" src="http://www.ibm.com/i/c.gif" width="100" border="0" />
								</td>
						</tr>
						<tr valign="top">
								<td bgcolor="#ffffff" colspan="5">
										<img height="8" alt="" src="http://www.ibm.com/i/c.gif" width="100" border="0" />
								</td>
						</tr>
				</tbody>
		</table>
		<table cellspacing="0" cellpadding="0" width="100%" border="0">
				<tbody>
						<tr valign="top">
								<td width="5"> </td>
								<td width="100%">
										<table cellspacing="0" cellpadding="0" width="168" align="right" border="0">
												<tbody>
														<tr>
																<td width="8">
																		<img height="21" alt="" src="http://www.ibm.com/i/c.gif" width="5" />
																</td>
																<td width="160">
																		<img height="21" alt="" src="http://www.ibm.com/i/c.gif" width="160" />
																</td>
														</tr>
												</tbody>
										</table>
										<!-- begin translation here -->
										<p>IBM developerWorks 提供了三种下载方法：FTP、HTTP 以及用于大文件下载的下载助手（ Download Director）。大多数情况下，FTP 要比 HTTP 更可靠，并可缩短下载时间。最新的浏览器在进行 FTP 下载时会显示时间估计和传输速度。在有些情况下，浏览器还可以续传中断的 FTP 下载。要利用 FTP 的这种方便性，在使用 HTTP 下载之前首先尝试一下 FTP 下载方式。</p>
										<p>如果您使用 FTP 穿过防火墙下载时遇到了问题，再试用 HTTP 下载。虽然使用 HTTP 方式进行大文件下载时不如 FTP 可靠，但 Internet Explore<img height="1" alt="" src="http://www.ibm.com/i/c.gif" width="5" border="0" />r 5.01 及以上版本有时能够恢复中断的 HTTP 下载。HTTP 下载能够穿过防火墙，因为它使用了端口号 80 来进行数据传输。以下下载行为和错误可能是遇到了防火墙问题：</p>
										<ul xmlns:dw="http://www.ibm.com/developerWorks/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
												<li>临近结束但又没有完成时下载突然停止。 
</li>
												<li>每次在同一地方停止下载。 
</li>
												<li>错误 400 表示代理加载失败。 
</li>
												<li>出现一条消息表明文件类型未找到。 
</li>
												<li>出现一条消息表明页面已经移走。 </li>
										</ul>
								</td>
						</tr>
				</tbody>
		</table>
<img src ="http://www.cppblog.com/Jeff-Chen/aggbug/5525.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.cppblog.com/Jeff-Chen/" target="_blank">Jeff-Chen</a> 2006-04-14 12:00 <a href="http://www.cppblog.com/Jeff-Chen/archive/2006/04/14/5525.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item><item><title>用 Eclipse 和 Ant 进行 Python 开发</title><link>http://www.cppblog.com/Jeff-Chen/archive/2006/04/14/5521.html</link><dc:creator>Jeff-Chen</dc:creator><author>Jeff-Chen</author><pubDate>Fri, 14 Apr 2006 03:34:00 GMT</pubDate><guid>http://www.cppblog.com/Jeff-Chen/archive/2006/04/14/5521.html</guid><wfw:comment>http://www.cppblog.com/Jeff-Chen/comments/5521.html</wfw:comment><comments>http://www.cppblog.com/Jeff-Chen/archive/2006/04/14/5521.html#Feedback</comments><slash:comments>1</slash:comments><wfw:commentRss>http://www.cppblog.com/Jeff-Chen/comments/commentRss/5521.html</wfw:commentRss><trackback:ping>http://www.cppblog.com/Jeff-Chen/services/trackbacks/5521.html</trackback:ping><description><![CDATA[
		<table cellspacing="0" cellpadding="0" width="100%" border="0">
				<tbody>
						<tr valign="top">
								<td width="100%">
										<h1>用 Eclipse 和 Ant 进行 Python 开发</h1>
										<p id="subtitle">用 Eclipse IDE 和 Apache Ant 构建工具进行 Python 开发</p>
										<img class="display-img" height="6" alt="" src="http://www.ibm.com/i/c.gif" width="1" />
								</td>
								<td class="no-print" width="192">
										<img height="18" alt="developerWorks" src="http://www-128.ibm.com/developerworks/cn/i/dw.gif" width="192" />
								</td>
						</tr>
				</tbody>
		</table>
		<table cellspacing="0" cellpadding="0" width="100%" border="0">
				<tbody>
						<tr valign="top">
								<td width="10">
										<img height="1" alt="" src="http://www.ibm.com/i/c.gif" width="10" />
								</td>
								<td width="100%">
										<table class="no-print" cellspacing="0" cellpadding="0" width="160" align="right" border="0">
												<tbody>
														<tr>
																<td width="10">
																		<img height="1" alt="" src="http://www.ibm.com/i/c.gif" width="10" />
																</td>
																<td>
																		<table cellspacing="0" cellpadding="0" width="150" border="0">
																				<tbody>
																						<tr>
																								<td class="v14-header-1-small">文档选项</td>
																						</tr>
																				</tbody>
																		</table>
																		<table class="v14-gray-table-border" cellspacing="0" cellpadding="0" border="0">
																				<tbody>
																						<tr>
																								<td class="no-padding" width="150">
																										<table cellspacing="0" cellpadding="0" width="143" border="0">
																												<img height="1" alt="" src="http://www.ibm.com/i/c.gif" width="8" />
																												<form name="email" action="https://www-128.ibm.com/developerworks/secure/email-it.jsp">
																														<input type="hidden" value="Python 是一种非常灵活强大的动态脚本编程语言，具有完整的面向对象特性。本文着重介绍了如何使用基于 Java 技术的流行开发工具 Eclipse 和 Ant 进行 Python 开发。" name="body" />
																														<input type="hidden" value="用 Eclipse 和 Ant 进行 Python 开发" name="subject" />
																														<input type="hidden" value="cn" name="lang" />
																														<script language="JavaScript" type="text/javascript">
																																<!--
document.write('<tr valign="top"><td width="8"><img src="//www.ibm.com/i/c.gif" width="8" height="1" alt=""/></td><td width="16"><img src="//www.ibm.com/i/v14/icons/em.gif" height="16" width="16" vspace="3" alt="将此页作为电子邮件发送" /></td><td width="122"><p><a class="smallplainlink" href="javascript:document.email.submit();"><b>将此页作为电子邮件发送</b></a></p></td></tr>');
//-->
																														</script>
																														<tbody>
																																<tr valign="top">
																																		<td width="8">
																																				<img height="1" alt="" src="http://www.ibm.com/i/c.gif" width="8" />
																																		</td>
																																		<td width="16">
																																				<img height="16" alt="将此页作为电子邮件发送" src="http://www.ibm.com/i/v14/icons/em.gif" width="16" vspace="3" />
																																		</td>
																																		<td width="122">
																																				<p>
																																						<a class="smallplainlink" href="javascript:document.email.submit();">
																																								<b>
																																										<font color="#5c81a7" size="2">将此页作为电子邮件发送</font>
																																								</b>
																																						</a>
																																				</p>
																																		</td>
																																</tr>
																																<noscript>
																																		<tr valign="top">
																																				<td width="8">
																																						<img alt="" height="1" width="8" src="//www.ibm.com/i/c.gif" />
																																				</td>
																																				<td width="16">
																																						<img alt="" width="16" height="16" src="//www.ibm.com/i/c.gif" />
																																				</td>
																																				<td class="small" width="122">
																																						<p>
																																								<span class="ast">未显示需要 JavaScript 的文档选项</span>
																																						</p>
																																				</td>
																																		</tr>
																																</noscript>
																														</tbody>
																												</form>
																										</table>
																								</td>
																						</tr>
																				</tbody>
																		</table>
																</td>
														</tr>
												</tbody>
										</table>
										<!--START RESERVED FOR FUTURE USE INCLUDE FILES-->
										<!-- 03/20/06 updated by gretchen -->
										<br />
										<table cellspacing="0" cellpadding="0" width="150" border="0">
												<tbody>
														<tr>
																<td class="v14-header-2-small">最新推荐</td>
														</tr>
												</tbody>
										</table>
										<table class="v14-gray-table-border" cellspacing="0" cellpadding="0" border="0">
												<tbody>
														<tr>
																<td class="no-padding" width="150">
																		<table cellspacing="0" cellpadding="0" width="143" border="0">
																				<tbody>
																						<tr valign="top">
																								<td width="8">
																										<img height="1" alt="" src="http://www.ibm.com/i/c.gif" width="8" />
																								</td>
																								<td>
																										<img height="16" alt="" src="http://www.ibm.com/i/v14/icons/fw_bold.gif" width="16" vspace="3" border="0" />
																								</td>
																								<td width="125">
																										<p>
																												<a class="smallplainlink" href="http://www-128.ibm.com/developerworks/cn/kickstart/">
																														<font color="#5c81a7" size="2">Java 应用开发源动力 － 下载免费软件，快速启动开发</font>
																												</a>
																										</p>
																								</td>
																						</tr>
																				</tbody>
																		</table>
																</td>
														</tr>
												</tbody>
										</table>
										<!--END RESERVED FOR FUTURE USE INCLUDE FILES-->
										<br />
								</td>
						</tr>
				</tbody>
		</table>
		<p>级别: 初级</p>
		<p>
				<a href="http://www-128.ibm.com/developerworks/cn/opensource/os-ecant/index.html#author">
						<font color="#996699">Ron Smith</font>
				</a>, 负责人<br /></p>
		<p>2004 年 6 月 01 日</p>
		<blockquote>Python 是一种非常灵活强大的动态脚本编程语言，具有完整的面向对象特性。众多的支持者指出，Python 语言与其他语言相比能更快更有效地表达出他们的意图。但是从 Java 技术™ 或 Microsoft® .NET 刚刚转到 Python 的人会发现，功能丰富而精致的 IDE 和开发工具都不见了。那些开发人员可以从他们熟悉的 Java 开发工具中找到解决方案。本文着重介绍了如何使用基于 Java 技术的流行开发工具 Eclipse 和 Ant 进行 Python 开发。</blockquote>
		<!--START RESERVED FOR FUTURE USE INCLUDE FILES-->
		<!-- include java script once we verify teams wants to use this and it will work on dbcs and cyrillic characters -->
		<!--END RESERVED FOR FUTURE USE INCLUDE FILES-->
		<p>
				<a name="N1003D">
						<span class="atitle">
								<font face="Arial" size="4">简介</font>
						</span>
				</a>
		</p>
		<p>多年以来， Java 语言和 Python 阵营之间一直存在大量的异花授粉现象。在这方面作出突出表率的可能是 Jython。这是一个纯粹用 Java 实现的 Python 运行时环境。按照这一说法，您将研究如何用 Eclipse IDE 和 Ant 构建与部署工具实现 Python 开发。Eclipse 和 Ant 是非常流行的工具，它们特性丰富、可扩展性强、而且开放源代码；Python 也具有相同的品质。PyDev 和 PyAntTasks 分别是 Eclipse 和 Ant 的扩展，有了它们就可能用这些 Java 工具开发 Python。本文从下载安装所需的工具与扩展开始讲起。为了解释如何在 Python 开发中使用 Eclipse 和 Ant，我将用实际的 Python 代码例子读取 RSS 资源。 </p>
		<p>本文不会涉及 Eclipse、Ant、Python 的细节。有关这些话题的深入讨论，请参阅 <a href="http://www-128.ibm.com/developerworks/cn/opensource/os-ecant/index.html#resources"><font color="#996699">参考资料</font></a> 一节中的链接。 </p>
		<p>
				<a name="N1004D">
						<span class="smalltitle">
								<strong>
										<font face="Arial">Python 支持情况</font>
								</strong>
						</span>
				</a>
		</p>
		<p>本文用到的软件都在 CPython 2.3 下测试过。除了几个异常情况之外，应该也能在 Jython 中运行。特别需要指出，PyDev 调试器目前不支持 Jython。另一个区别是通过 Jython 执行的脚本在从 PyDev 中运行之后就转入交互模式，这样就必须手动杀死。PyDev 编辑器与 Jython 的源代码兼容，Python Ant 任务除 py-doc 任务之外也和 Jython 兼容。 </p>
		<br />
		<table cellspacing="0" cellpadding="0" width="100%" border="0">
				<tbody>
						<tr>
								<td>
										<img height="1" alt="" src="http://www.ibm.com/i/v14/rules/blue_rule.gif" width="100%" />
										<br />
										<img height="6" alt="" src="http://www.ibm.com/i/c.gif" width="8" border="0" />
								</td>
						</tr>
				</tbody>
		</table>
		<table class="no-print" cellspacing="0" cellpadding="0" align="right">
				<tbody>
						<tr align="right">
								<td>
										<img height="4" alt="" src="http://www.ibm.com/i/c.gif" width="100%" />
										<br />
										<table cellspacing="0" cellpadding="0" border="0">
												<tbody>
														<tr>
																<td valign="center">
																		<img height="16" alt="" src="http://www.ibm.com/i/v14/icons/u_bold.gif" width="16" border="0" />
																		<br />
																</td>
																<td valign="top" align="right">
																		<a class="fbox" href="http://www-128.ibm.com/developerworks/cn/opensource/os-ecant/index.html#main">
																				<b>
																						<font color="#996699">回页首</font>
																				</b>
																		</a>
																</td>
														</tr>
												</tbody>
										</table>
								</td>
						</tr>
				</tbody>
		</table>
		<br />
		<br />
		<p>
				<a name="N10056">
						<span class="atitle">
								<font face="Arial" size="4">使用 Eclipse 进行 Python 开发</font>
						</span>
				</a>
		</p>
		<p>
				<a name="N1005C">
						<span class="smalltitle">
								<strong>
										<font face="Arial">Eclipse 概述</font>
								</strong>
						</span>
				</a>
		</p>
		<p>Eclipse 是一个 Java 技术集成开发环境，由 IBM 开发，并开放其源代码。它是 IBM 商业软件 WebSphere Application Development 环境以及其他多种工具的基础。Eclipse 的开发社区非常活跃，他们不仅开发 Eclipse 本身，还开发大量的插件供 Eclipse 使用。有关 Eclispe 和 Eclipse 插件的 Web 站点，请参阅 <a href="http://www-128.ibm.com/developerworks/cn/opensource/os-ecant/index.html#resources"><font color="#996699">参考资料</font></a> 一节中的链接。尽管从传统上讲 Eclipse 是一种 Java 开发工具，但是一些插件的存在使得在 Eclipse 中开发其他语言的程序成为可能，如 C/C++、Python 和 Perl。 </p>
		<p>在 Eclipse 中，源代码被组织到项目（project）中。项目可以加载、卸载和导入。Eclipse 用户界面的结构划分为视图（View）与编辑器（Editor）。视图与编辑器的例子包括：源代码大纲视图、Java 源代码编辑器、Python 源代码编辑器和文件系统导航视图。Eclipse 用户界面中最关键的隐含概念就是 <i>视角（perspective）</i>。视角是通常在执行某种类型活动时一起使用的一组视图。Eclipse 中的标准视角包括：Debug、Java Browsing、Java、Java Type Hierarchy、Plug-in Development、CVS Repository Exploring、Resource 和 Install/Update。目前还不存在单独的 Python 视角。在进行 Python 开发时，我通常使用 Resource 视角和 Debug 视角。 </p>
		<p>
				<a name="N1006F">
						<span class="smalltitle">
								<strong>
										<font face="Arial">安装 PyDev</font>
								</strong>
						</span>
				</a>
		</p>
		<p>首先，从 Eclipse Web 站点上下载 Eclipse（请参阅 <a href="http://www-128.ibm.com/developerworks/cn/opensource/os-ecant/index.html#resources"><font color="#996699">参考资料</font></a> 一节中的链接），并根据您的平台，按照下面的安装指南安装 Eclipse： </p>
		<p>Eclipse 的更新机制使 PyDev 插件的安装更加容易。从 Eclipse 中选择 <b>Help &gt; Software Updates &gt; Update Manager</b>，启动 Install/Update 视角。在左下角的 Feature Updates 视图中，将 PyDev 插件更新站点作为新的 Site Bookmark 添加到“Sites to Visit”文件夹下。Eclipse 的 PyDev 更新站点 URL 为 http://pydev.sf.net/updates/。现在，Feature Updates 编辑器中应该显示出“PyDev”这一特性。在 Feature Updates 编辑器中，展开 <b>PyDev &gt; Other</b>，选择其中显示的 PyDev 特性（至少应该是 0.4.1）。然后选择 “Install Now”安装该特性。Eclipse 将下载 PyDev 插件，并将其安装到 Eclipse 中。 </p>
		<p>
				<a name="N10085">
						<span class="smalltitle">
								<strong>
										<font face="Arial">导入样例项目</font>
								</strong>
						</span>
				</a>
		</p>
		<p>为访问本项目中使用的样例代码，可先下载 zip 文件（请参阅 <a href="http://www-128.ibm.com/developerworks/cn/opensource/os-ecant/index.html#resources"><font color="#996699">参考资料</font></a>一节），在文件系统中展开该 zip 文件，然后将其中的项目导入 Eclipse。导入项目的方法是先切换到 Resource 视角，选择 <b>File &gt; Import</b>，再选择“Existing Project into Workspace”，然后选择您展开 zip 文件的位置。这时，Navigator 视图中应该出现 feedParserTest 项目。 </p>
		<p>样例项目中已经包含了 Fead Parser 通用资源解析库，该库按 Python 开放源代码许可协议发布。有关 Feed Parser 项目 Web 网站的链接，请参阅 <a href="http://www-128.ibm.com/developerworks/cn/opensource/os-ecant/index.html#resources"><font color="#996699">参考资料</font></a> 一节。 </p>
		<br />
		<table cellspacing="0" cellpadding="0" width="100%" border="0">
				<tbody>
						<tr>
								<td>
										<img height="1" alt="" src="http://www.ibm.com/i/v14/rules/blue_rule.gif" width="100%" />
										<br />
										<img height="6" alt="" src="http://www.ibm.com/i/c.gif" width="8" border="0" />
								</td>
						</tr>
				</tbody>
		</table>
		<table class="no-print" cellspacing="0" cellpadding="0" align="right">
				<tbody>
						<tr align="right">
								<td>
										<img height="4" alt="" src="http://www.ibm.com/i/c.gif" width="100%" />
										<br />
										<table cellspacing="0" cellpadding="0" border="0">
												<tbody>
														<tr>
																<td valign="center">
																		<img height="16" alt="" src="http://www.ibm.com/i/v14/icons/u_bold.gif" width="16" border="0" />
																		<br />
																</td>
																<td valign="top" align="right">
																		<a class="fbox" href="http://www-128.ibm.com/developerworks/cn/opensource/os-ecant/index.html#main">
																				<b>
																						<font color="#996699">回页首</font>
																				</b>
																		</a>
																</td>
														</tr>
												</tbody>
										</table>
								</td>
						</tr>
				</tbody>
		</table>
		<br />
		<br />
		<p>
				<a name="N1009C">
						<span class="atitle">
								<font face="Arial" size="4">PyDev 漫游</font>
						</span>
				</a>
		</p>
		<p>现在开始学习如何通过已导入的项目了解 PyDev 的特性。PyDev 正处于开发过程中，但已经是非常高效的 Python 开发环境。现在的 PyDev 主要包括以下特性：</p>
		<ul>
				<li>包含 Python 语法高亮显示特性的 Python 编辑器。 
</li>
				<li>进行 Python 语法分析，并在 Python 编辑器和 Tasks 视图中高亮显示错误。 
</li>
				<li>可将制表符转换成空格的选项。 
</li>
				<li>Outline 视图显示导入的库、类以及函数。 
</li>
				<li>终端视图中的 Python 堆栈跟踪信息可超链接到源代码中。 
</li>
				<li>源代码内部的超链接；同一模块内的导入和函数调用可通过超链接进行导航。 
</li>
				<li>从 Navigator 视图中运行 Python 脚本的能力。 
</li>
				<li>调试器支持断点、代码单步执行以及显示变量的值。 </li>
		</ul>
		<p>
				<a name="N100C0">
						<span class="smalltitle">
								<strong>
										<font face="Arial">PyDev 选项窗口</font>
								</strong>
						</span>
				</a>
		</p>
		<p>通过 <b>Window &gt; Preferences</b>，并选择 PyDev（请参阅图 1），便可访问 PyDev 选项。第一组选项可以改变 PyDev 在源代码中处理制表符的方式，还可以改变语法元素的颜色。 </p>
		<br />
		<a name="N100CE">
				<b>图 1. PyDev 选项窗口</b>
		</a>
		<br />
		<img alt="PyDev 选项窗口" src="http://www-128.ibm.com/developerworks/cn/opensource/os-ecant/pyDevPrefs.jpg" />
		<br />
		<p>
				<a name="N100DB">
						<span class="smalltitle">
								<strong>
										<font face="Arial">设置 Python 解释器</font>
								</strong>
						</span>
				</a>
		</p>
		<p>PyDev Debug 选项可以选择 Python 解释器，供执行 Python 代码时使用。如果 PyDev 无法找到 Python 解释器，或者想使用别的解释器，可在此设置（请参阅图 2）。 </p>
		<br />
		<a name="N100E6">
				<b>图 2. PyDev Debug 选项</b>
		</a>
		<br />
		<img alt="PyDev Debug 选项" src="http://www-128.ibm.com/developerworks/cn/opensource/os-ecant/pyDevDebugPrefs.jpg" />
		<br />
		<p>
				<a name="N100F3">
						<span class="smalltitle">
								<strong>
										<font face="Arial">处理源代码</font>
								</strong>
						</span>
				</a>
		</p>
		<p>我的大部分 Python 工作都是在 Resource 视角中完成的。使用方法是先切换到 Resource 视角，然后在左上角的 Navigator 视图中双击 feedParserTest/src/feedparserTest/FeedparserTest.py 文件。Python 编辑器打开该文件，对 Python 语法进行解析，完成设置颜色和语法检查的工作（请参阅图 3）。 </p>
		<br />
		<a name="N100FE">
				<b>图 3. Python 编辑器</b>
		</a>
		<br />
		<img alt="Python 编辑器" src="http://www-128.ibm.com/developerworks/cn/opensource/os-ecant/pythonEditor.jpg" />
		<br />
		<p>如果源代码中有任何错误，则显示在右下角的 Tasks 视图中显示出来。双击 Tasks 视图中的错误，便可找到那条讨厌的代码行。 </p>
		<p>Outline 视图在左下角，其中用一种便于浏览的结构显示出当前正在编辑的文件。导入的库、类、函数全都显示出来，通过双击 Outline 视图中的项目，便可以实现导航。PyDev 在编辑 Python 文件的过程中对齐进行预先解析的工作，同时更新 Outline 视图，执行语法检查，并用不同颜色显示语法元素。 </p>
		<p>
				<a name="N10111">
						<span class="smalltitle">
								<strong>
										<font face="Arial">编辑器的特性</font>
								</strong>
						</span>
				</a>
		</p>
		<p>PyDev 0.4 版在 Python 源代码编辑器中为函数和导入库加入了超链接的特性。如果在越过某项导入或函数调用（必须在 <code>PYTHONPATH</code> 目录中）的同时按下 Control 键，PyDev 就能显示出一个超链接，这样您可以在导入库或函数的源代码之间导航。请注意，为了在您自己的源代码中跨模块使用该特性（从一个模块链接到另一个模块），必须修改 <code>PYTHONPATH</code> 环境变量，在其中加入这些模块，这样 PyDev 就可以找到它们了。 </p>
		<p>人们已经开始将一些优异的源代码编辑特性加入最新版本的 PyDev 中，其中就包括代码块注释与取消注释，以及代码左右移位（请参阅图 4）。 </p>
		<br />
		<a name="N10127">
				<b>图 4. PyDev 编辑器的其他特性</b>
		</a>
		<br />
		<img alt="PyDev 编辑器的其他特性" src="http://www-128.ibm.com/developerworks/cn/opensource/os-ecant/editorFeatures.jpg" />
		<br />
		<p>
				<a name="N10134">
						<span class="smalltitle">
								<strong>
										<font face="Arial">运行 Python 脚本</font>
								</strong>
						</span>
				</a>
		</p>
		<p>如果不能执行代码，那么 IDE 也不是太有用。为执行 Python 代码，可从 Navigator 视图中选择 feedparser.py 文件，用右键点击，然后选择 <b>Python &gt; Run</b>。随后会显示 Python 的启动配置窗口（请参阅图 5）。 </p>
		<br />
		<a name="N10142">
				<b>图 5. Python 启动配置</b>
		</a>
		<br />
		<img alt="Python 启动配置" src="http://www-128.ibm.com/developerworks/cn/opensource/os-ecant/pythonLaunch.jpg" />
		<br />
		<p>Python 启动配置窗口中可以定义脚本执行的当前目录，传递给脚本的参数，以及用哪一个 Python 解释器运行脚本。feedparser.py 以一个 RSS URL 作为参数，所以可在参数字段中填入 URL，如 http://www.ibm.com/developerworks/news/dw_dwtp.rss。其余的缺省定义就可以了，所以单击 <b>Run</b>。 </p>
		<p>脚本执行时输出信息显示在 Console 窗口中。如果有错误出现，Console 窗口中将显示堆栈跟踪信息，其中的每一行都可以通过超链接找到 Python 源代码。 </p>
		<p>
				<a name="N10158">
						<span class="smalltitle">
								<strong>
										<font face="Arial">Python 调试器</font>
								</strong>
						</span>
				</a>
		</p>
		<p>Python 调试器是最近才加入 PyDev 插件中的。要使用调试器，可在 Python 编辑器中想中断的代码行的左侧点击，设置断点。在图 6 中，我在 feedparser.py 的 1830 行处设置了断点。然后在 Navigator 视图中选择这个 Python 模块，点击右键，选择“Python &gt; Debug...”。这时将显示与前面相似的一个启动配置窗口。点击 <b>Debug</b> 进入 Debug 视角，同时启动调试器。 </p>
		<br />
		<a name="N10166">
				<b>图 6. Python 调试器</b>
		</a>
		<br />
		<img alt="Python 调试器" src="http://www-128.ibm.com/developerworks/cn/opensource/os-ecant/debugger.jpg" />
		<br />
		<p>左上角的 Debug 视图显示当前正在执行的进程和线程，右上角的 Variables 视图显示当前运行域中的所有变量，Python 编辑器会显示调试器目前停在哪条语句上，同时所有的输出信息都显示与 Console 视图中。调试器可以通过 Debug 视图底部的按钮或 Run 菜单进行控制。 </p>
		<p>
				<a name="N10176">
						<span class="smalltitle">
								<strong>
										<font face="Arial">其他 Eclipse 特性</font>
								</strong>
						</span>
				</a>
		</p>
		<p>Eclipse 及其插件还具备很多其他的特性，可应用于 Python 开发中，如 XML 编辑器、UML 编辑器（不过大多数是以 Java 代码为中心），还有资源控制方面的插件。目前 Eclipse 插件站点上列出的插件几乎有 500 个（请参阅 <a href="http://www-128.ibm.com/developerworks/cn/opensource/os-ecant/index.html#resources"><font color="#996699">参考资料</font></a> 一节中的相关链接）。我将着重介绍一个对很多 Python 开发人员都特别有用的插件：Eclipse 发行版中已经包括的 CVS 插件，不过不会讨论细节内容。 </p>
		<p>Eclipse 中包括特性丰富的集成 CVS：</p>
		<ul>
				<li>支持 SSH、pserver、ext 等连接方法。 
</li>
				<li>基本 CVS 命令的支持：检出项目、提交变更、更新、向.cvsignore 中增加文件或模式等等。 
</li>
				<li>文件合并查看。 
</li>
				<li>在源代码控制中实现对文件不同之处的比较。 
</li>
				<li>项目同步，并用资料库显示出删除和新增的内容。 </li>
		</ul>
		<p>还可以通过提供其他插件来支持其他源代码控制系统，如 ClearCase、Subversion、Visual SourceSafe 等。 </p>
		<br />
		<table cellspacing="0" cellpadding="0" width="100%" border="0">
				<tbody>
						<tr>
								<td>
										<img height="1" alt="" src="http://www.ibm.com/i/v14/rules/blue_rule.gif" width="100%" />
										<br />
										<img height="6" alt="" src="http://www.ibm.com/i/c.gif" width="8" border="0" />
								</td>
						</tr>
				</tbody>
		</table>
		<table class="no-print" cellspacing="0" cellpadding="0" align="right">
				<tbody>
						<tr align="right">
								<td>
										<img height="4" alt="" src="http://www.ibm.com/i/c.gif" width="100%" />
										<br />
										<table cellspacing="0" cellpadding="0" border="0">
												<tbody>
														<tr>
																<td valign="center">
																		<img height="16" alt="" src="http://www.ibm.com/i/v14/icons/u_bold.gif" width="16" border="0" />
																		<br />
																</td>
																<td valign="top" align="right">
																		<a class="fbox" href="http://www-128.ibm.com/developerworks/cn/opensource/os-ecant/index.html#main">
																				<b>
																						<font color="#996699">回页首</font>
																				</b>
																		</a>
																</td>
														</tr>
												</tbody>
										</table>
								</td>
						</tr>
				</tbody>
		</table>
		<br />
		<br />
		<p>
				<a name="N1019B">
						<span class="atitle">
								<font face="Arial" size="4">在 Eclipse 中使用 Python 的交互式 shell</font>
						</span>
				</a>
		</p>
		<p>Python 解释器支持 Python 代码的交互式执行。这种方式对于调试一段代码是非常有用的，因为不用把代码放进 Python 脚本中并执行脚本了。同时，Python 解释器的交互模式可以很容易地集成到 Eclipse 中。 </p>
		<p>要增加对 Python 交互式执行的支持，可通过 <b>Run &gt; External Tools &gt; External Tools</b> 增加一个 External Tool 启动程序。这时将打开 External Tool 启动程序配置窗口。在 Configurations 列表中选择“Program”，然后点击“New”创建一个新的配置。将该配置命名为诸如 "pythonInteractive" 之类，然后设置 Location，令其指向您的 Python 解释器，接着，将 "-i" 作为唯一的参数传递进来（请参阅图 7）。 </p>
		<p>在 Common 选项卡下，选中复选框，使该配置在 External Tools 收藏夹菜单中显示出来。 </p>
		<br />
		<a name="N101AF">
				<b>图 7. Python 交互方式配置</b>
		</a>
		<br />
		<img alt="Python 交互方式配置" src="http://www-128.ibm.com/developerworks/cn/opensource/os-ecant/pythonInteractiveConfig.jpg" />
		<br />
		<p>要运行刚刚在 Eclipse 中创建的启动器，可选择 <b>Run &gt; External Tools &gt; pythonInterpreter</b>。Python 解释器的输出显示在 Console 视图中。Console 中可输入 Python 命令并执行，就像从命令行中执行 Python 一样。为导入并在交互模式下使用模块，您需要将模块的位置增加到 <code>PYTHONPATH</code> 环境变量中。 </p>
		<p>在 Eclipse Console 中执行 Python 与用命令行执行的不同之处在于，无法启用命令历史特性（通过向上和向下的方向键实现），因为 Eclipse Console 会自己解释这些键。 </p>
		<br />
		<table cellspacing="0" cellpadding="0" width="100%" border="0">
				<tbody>
						<tr>
								<td>
										<img height="1" alt="" src="http://www.ibm.com/i/v14/rules/blue_rule.gif" width="100%" />
										<br />
										<img height="6" alt="" src="http://www.ibm.com/i/c.gif" width="8" border="0" />
								</td>
						</tr>
				</tbody>
		</table>
		<table class="no-print" cellspacing="0" cellpadding="0" align="right">
				<tbody>
						<tr align="right">
								<td>
										<img height="4" alt="" src="http://www.ibm.com/i/c.gif" width="100%" />
										<br />
										<table cellspacing="0" cellpadding="0" border="0">
												<tbody>
														<tr>
																<td valign="center">
																		<img height="16" alt="" src="http://www.ibm.com/i/v14/icons/u_bold.gif" width="16" border="0" />
																		<br />
																</td>
																<td valign="top" align="right">
																		<a class="fbox" href="http://www-128.ibm.com/developerworks/cn/opensource/os-ecant/index.html#main">
																				<b>
																						<font color="#996699">回页首</font>
																				</b>
																		</a>
																</td>
														</tr>
												</tbody>
										</table>
								</td>
						</tr>
				</tbody>
		</table>
		<br />
		<br />
		<p>
				<a name="N101C9">
						<span class="atitle">
								<font face="Arial" size="4">在 Python 开发中使用 Ant</font>
						</span>
				</a>
		</p>
		<p>Python 会在它需要的时候自动编译模块。这意味着 Python 开发人员通常不必显式地对模块进行编辑。即便如此，有时候手工编译 Python 代码还是很有用的，同时，构建和部署过程中还有很多其他方面的内容可以自动化实现。这也正是构建工具的用武之地。 </p>
		<p>我将着重介绍来自 Java 编程世界中的 Apache Ant，这个工具可大量应用在 Python 开发中。Apache Ant 是 Java 编程领域内事实上的标准构建工具。它更加轻便，与 Java 技术结合得更好，可用于替代其他的构建工具。Ant 可以在支持 Java 编程语言的任何一种平台上运行。尽管我们需要的大多数构建特性 Ant 都已经提供了，但如果要将 Ant 用做 Python 构建工具，还是需要有一些关键的与 Python 相关的特性。我已经开发了若干定制的 Ant 插件（用 Ant 的行话讲叫做 task），可提供构建 Python 时需要的特定于 Python 的特性。 </p>
		<p>Ant 用 XML 作为描述构建的格式。build 文件组织为需要执行的目标。每一个目标都可能依赖于其他的目标。Ant 将根据您所请求执行的目标，以及一组依赖目标，来执行任何需要的目标。每一个目标都可能包含任意数量的 Ant 任务，而由 Ant 任务实际执行目标的工作。Ant 有很多内置的任务，可以完成诸如编译 Java 代码、生成文档、操纵文件和目录，同时第三方又提供了很多附加的任务。 </p>
		<p>
				<a name="N101D8">
						<span class="smalltitle">
								<strong>
										<font face="Arial">安装 Python Ant 库</font>
								</strong>
						</span>
				</a>
		</p>
		<p>我将通过为 feedparser 项目创建构建脚本来介绍 Ant 构建脚本和 Python Ant 任务的基础知识。为了使用 Python Ant 任务，您需要下载并安装包含这些任务的 Java 库。首先，从 <a href="http://www-128.ibm.com/developerworks/cn/opensource/os-ecant/index.html#resources"><font color="#996699">参考资料</font></a> 一节中列出的 URL 中下载 Python Ant 任务库（pyAntTasks.jar）。然后，将 JAR 文件拷贝到 Eclipse 的 Ant 插件下的 lib 目录中。这应该是 Eclipse 安装目录下形如 plugins/org.apache.ant_1.5.3 的子目录。 </p>
		<p>Python Ant 任务库拷贝完毕之后，必须在 Eclipse 中启用库。选择 <b>Window &gt; Preferences</b>，然后选择 <b>Ant &gt; Runtime</b>。将 Ant Home Entries 展开，其中可看到 Eclipse 使用的库（JAR 文件）列表。选择“ Add JAR”，然后从 Eclipse Ant 插件的 lib 目录中选择 Python Ant JAR 文件，就可以将刚刚拷贝的 Python Ant JAR 文件加入库列表中（请参阅图 8）。 </p>
		<br />
		<a name="N101F0">
				<b>图 8. 向 classpath 中加入 Python Ant 任务</b>
		</a>
		<br />
		<img alt="向 classpath 中加入 Python Ant 任务" src="http://www-128.ibm.com/developerworks/cn/opensource/os-ecant/addPyAntTasks.jpg" />
		<br />
		<p>您现在应该能够创建和运行包含 Python 任务的 Ant 构建脚本了。下面进入构建脚本内部！ </p>
		<p>
				<a name="N10200">
						<span class="smalltitle">
								<strong>
										<font face="Arial">创建构建脚本</font>
								</strong>
						</span>
				</a>
		</p>
		<p>我将逐步介绍如何创建一个简单的 Python 构建脚本（请参阅清单 1）。完整的构建脚本 build.xml 可从 feedParserTest 项目的顶层目录中找到。 </p>
		<br />
		<a name="N10209">
				<b>清单 1. 用于编译 Python 源代码的构建脚本片断</b>
		</a>
		<br />
		<table cellspacing="0" cellpadding="5" width="100%" bgcolor="#eeeeee" border="1">
				<tbody>
						<tr>
								<td>
										<pre>
												<code class="section">
														<font face="Lucida Console">&lt;project name="feedParserTest" default="compile"&gt;

  &lt;taskdef resource="pyAntTasks.properties"/&gt;

  &lt;property name="src.dir" value="src"/&gt;

  &lt;target name="compile"&gt;
    &lt;py-compile dir="${src.dir}" pythonpath="${src.dir}" optimize="0"/&gt;
  &lt;/target&gt;

&lt;/project&gt;
</font>
												</code>
										</pre>
								</td>
						</tr>
				</tbody>
		</table>
		<br />
		<p>先介绍一个只编译 Python 样例代码的构建脚本。&lt;project&gt; 标签总是构建脚本的根标签。&lt;taskdef&gt; 标签声明在整个构建脚本中使用的 Python 任务。在构建脚本的底部，可以定义 <code>compile</code> 目标。目标元素内部是 <code>compile</code> 运行期间执行的任务。特别的是 py-compile 任务，它负责从 src 目录开始，编译所有的 Python 代码。该任务会递归遍历所有的子目录，并编译所有的 Python 模块。脚本中没有采用将 src 目录硬编码到调用之处的方式，而是在构建脚本中定义了称为 src.dir 的属性。然后，在需要使用这个目录名的时候，就可以通过 <code>${src.dir}</code> 来引用。 </p>
		<p>要运行构建脚本，可从 Eclipse 中打开它。Eclipse 具有内置的 Ant 构建脚本编辑和浏览功能。Outline 视图可以显示出构建脚本的结构。在 Navigator 视图中，选择该构建脚本，用右键点击，然后选择“Run Ant...”。选择 <code>compile</code> 目标，然后点击“Run”。构建脚本执行过程中的输出信息应该显示在 Console 视图中，表示运行成功。 </p>
		<p>
				<a name="N10229">
						<span class="smalltitle">
								<strong>
										<font face="Arial">Python 脚本执行任务</font>
								</strong>
						</span>
				</a>
		</p>
		<p>接下来将向构建脚本中加入新的目标，用于执行 Python 脚本（请参阅清单 2）。在本例中，可以将 RSS URL 作为参数来执行 feedparser.py 脚本。 </p>
		<br />
		<a name="N10232">
				<b>清单 2. 运行 feedparser 脚本的构建脚本片断</b>
		</a>
		<br />
		<table cellspacing="0" cellpadding="5" width="100%" bgcolor="#eeeeee" border="1">
				<tbody>
						<tr>
								<td>
										<pre>
												<code class="section">
														<font face="Lucida Console">  &lt;target name="run.feedparser" depends="compile"&gt;
    &lt;py-run script="src/feedparser/feedparser.py" pythonpath="${src.dir}" optimize="0"&gt;
      &lt;arg value="http://www.ibm.com/developerworks/news/dw_dwtp.rss"&gt;
    &lt;/py-run&gt;
  &lt;/target&gt;

</font>
												</code>
										</pre>
								</td>
						</tr>
				</tbody>
		</table>
		<br />
		<p>上面的目标以 RSS URL 为唯一的参数来执行 feedparser.py 脚本。该目标声明为依赖于 <code>compile</code> 目标，所以后者将首先执行。实际上这一步并不是很必要，因为 Python 会根据需要自动编译源代码。如果您执行 <code>run.feedparser</code> 目标，就会运行 feedparser.py 脚本，同时将 RSS 的内容输出到 Console 中。 </p>
		<p>
				<a name="N10247">
						<span class="smalltitle">
								<strong>
										<font face="Arial">Python 文档任务</font>
								</strong>
						</span>
				</a>
		</p>
		<p>Python 的 API 文档编制机制与 Java 技术中的 JavaDoc 系统类似，称为 PyDoc。在构建脚本中加入清单 3 中列出的如下 XML 片断，可为所有的 Python 模块生成 PyDoc。 </p>
		<br />
		<a name="N10250">
				<b>清单 3. 用于生成 PyDoc 的构建脚本片断</b>
		</a>
		<br />
		<table cellspacing="0" cellpadding="5" width="100%" bgcolor="#eeeeee" border="1">
				<tbody>
						<tr>
								<td>
										<pre>
												<code class="section">
														<font face="Lucida Console"> 1:  &lt;property name="pydoc.dir" value="pydoc"/&gt;
 2:
 3:  &lt;target name="init"&gt;
 4:    &lt;mkdir dir="${pydoc.dir}"/&gt;
 5:  &lt;/target&gt;
 6:
 7:  &lt;target name="pydoc" depends="init,compile"&gt;
 8:    &lt;py-doc pythonpath="${src.dir}" destdir="${pydoc.dir}"&gt;
 9:      &lt;fileset dir="${src.dir}"&gt;
10:        &lt;include name="**/*"/&gt;
11:      &lt;/fileset&gt;
12:    &lt;/py-doc&gt;
13:  &lt;/target&gt;

</font>
												</code>
										</pre>
								</td>
						</tr>
				</tbody>
		</table>
		<br />
		<p>
				<code>从对上述 pydoc 目标的解析可看出，第 7 行声明了目标名称，并指出它依赖于 <code>init</code> 和 <code>compile</code> 目标。这意味着在运行 pydoc 目标之前，Ant 必须保证 <code>init</code> 和 <code>compile</code> 目标已经运行，如果没有，则首先运行这两个目标。 </code>
		</p>
		<p>
				<code>pydoc</code> 目标所依赖的 <code>init</code> 目标在第 3 至第 5 行定义。 <code>init</code> 目标仅仅创建了一个存放 PyDoc API 文档文件的目录。如前所述，要为所生成文档的保存位置定义一个属性，名为 pydoc.dir。 </p>
		<p>第 8 行开始是 py-doc 任务。如前所述，您传入生成 pydoc 过程中所使用的 <code>PYTHONPATH</code> 。 <code>destdir</code> 属性告诉 py-doc 任务将生成的 HTML 文档输出到何处。 </p>
		<p>第 9 至第 11 行定义了在生成文档的过程中应该处理哪些 Python 源文件。文件集是 Ant 脚本中通用的结构，可用于定义所操作的一组文件。这是一种很强大的特性，它使您能够通过名字模式、布尔逻辑和文件属性来选择所要操作的文件。Ant 文档中有这方面的完整描述。本例中递归选择了“src”目录下的所有文件。 </p>
		<p>
				<a name="N1028D">
						<span class="smalltitle">
								<strong>
										<font face="Arial">Python 单元测试任务</font>
								</strong>
						</span>
				</a>
		</p>
		<p>Python 中具有标准的单元测试框架（从 Python 2.3 开始。在 Python 2.2 中这只是可选模块），与 Java jUnit 框架十分类似。测试用例的结构与 jUnit 采用相同的方式。每一个待测试的类和模块通常都具有自己的测试类。测试类中包含测试装置（fixture），它们在 <code>setUp</code> 函数中初始化。每一个测试都编写为测试类中的一个独立的测试函数。unittest 框架会在测试函数之间循环往复，先调用 <code>setUp</code> 、再测试函数、然后清除（ <code>tearDown</code> ）测试函数。请参阅清单 4 中的样例。 </p>
		<br />
		<a name="N102A2">
				<b>清单 4. Python 单元测试模块</b>
		</a>
		<br />
		<table cellspacing="0" cellpadding="5" width="100%" bgcolor="#eeeeee" border="1">
				<tbody>
						<tr>
								<td>
										<pre>
												<code class="section">
														<font face="Lucida Console">import unittest
from pprint import pprint

import feedparser

class FeedparserTest(unittest.TestCase):
    """
    A test class for the feedparser module.
    """
    
    def setUp(self):
        """
        set up data used in the tests.
        setUp is called before each test function execution.
        """
        self.developerWorksUrl = "testData/developerworks.rss"       

    def testParse09Rss(self):
        """
        Test a successful run of the parse function for a
        0.91 RSS feed.
        """
        print "FeedparserTest.testParse09RSS()"
        
        result = feedparser.parse(self.developerWorksUrl)
        pprint(result)

        self.assertEqual(0, result['bozo'])
        
        self.assert_(result is not None)
        channel = result['channel']
        self.assert_(channel is not None)
        chanDesc = channel['description']
        self.assertEqual(u'The latest content from IBM developerWorks',
            chanDesc)
        
        items = result['items']
        self.assert_(items is not None)
        self.assert_(len(items)&gt; 3)
        firstItem = items[0]
        title = firstItem['title']
        self.assertEqual(u'Build installation packages with 
            solution installation and deployment technologies',
            title)
  
    def tearDown(self):
        """
        tear down any data used in tests
        tearDown is called after each test function execution.
        """
        pass
                
if __name__ == '__main__':
    unittest.main()
</font>
												</code>
										</pre>
								</td>
						</tr>
				</tbody>
		</table>
		<br />
		<p>上述清单是实现 feedparser 模块基本测试功能的测试类。完整的测试类见 feedParserTest 项目下的 src/feedparserTest/FeedparserTest.py。 <code>setUp</code> 函数负责准备整个测试过程中需要使用的测试装置，在本例中只有测试用的 RSS 文件的目录，测试函数将对其进行解析。 <code>testParse09Rss</code> 是真正的测试函数。这个函数调用 feedparser.parse 函数，传递测试用的 RSS 文件，输出解析结果，并通过 TestCase 类的 assert 函数执行基本的检查统作。如果任何 assert 的求值结果不是真，或是在执行过程中抛出任何异常，unittest 就会报告一次测试失败或错误。最后的两行负责在这个测试类内部运行测试，方法是直接运行该模块即可。 </p>
		<p>要独立运行该测试类，可以按前面所说的相同方式运行 FeedparserTest.py 模块。在 Eclipse Navigator 视图中选择 FeedparserTest.py，然后通过 <b>Python &gt; Run</b> 运行。此时显示启动配置窗口。除 Base 目录之外，其他都保持缺省值即可。Base 目录必须是 feedParserTest 项目的目录，这样才能在当前目录下找到 RSS 文件（testData/developerworks.rss）。修改 base 目录的设置，然后点击“Run”。输出信息显示在 Console 上。 </p>
		<p>您也许希望我们编写的所有单元测试都能够作为构建的一部分自动执行。将下面清单 5 所示的构建片断加入构建脚本便可实现。 </p>
		<br />
		<a name="N102C0">
				<b>清单 5. 执行单元测试的构建脚本片断</b>
		</a>
		<br />
		<table cellspacing="0" cellpadding="5" width="100%" bgcolor="#eeeeee" border="1">
				<tbody>
						<tr>
								<td>
										<pre>
												<code class="section">
														<font face="Lucida Console">1:  &lt;target name="tests" depends="compile"&gt;
2:	&lt;py-test pythonpath="${src.dir}" dir="."&gt;
3:  	  &lt;fileset dir="${src.dir}"&gt;
4:		&lt;include name="**/*Test.py"/&gt;
5:	  &lt;/fileset&gt;
6:  	&lt;/py-test&gt;
7:  &lt;/target&gt; 

</font>
												</code>
										</pre>
								</td>
						</tr>
				</tbody>
		</table>
		<br />
		<p>第一行是目标声明，这与其他的脚本相同。第 2 至第 6 行调用 py-test 任务。这部分代码将在“src”目录下查找所有以“Test.py”结尾的所有文件，并运行所有测试。 <code>PYTHONPATH</code> 设置为“src”，测试执行的当前工作目录就是当前目录（‘.’）。 </p>
		<p>运行目标的方法是先运行构建脚本，再选择执行“tests”目标。该目标将运行所有以“Test.py”结尾的测试用例，本例中仅有 FeadparserTest.py。 </p>
		<br />
		<table cellspacing="0" cellpadding="0" width="100%" border="0">
				<tbody>
						<tr>
								<td>
										<img height="1" alt="" src="http://www.ibm.com/i/v14/rules/blue_rule.gif" width="100%" />
										<br />
										<img height="6" alt="" src="http://www.ibm.com/i/c.gif" width="8" border="0" />
								</td>
						</tr>
				</tbody>
		</table>
		<table class="no-print" cellspacing="0" cellpadding="0" align="right">
				<tbody>
						<tr align="right">
								<td>
										<img height="4" alt="" src="http://www.ibm.com/i/c.gif" width="100%" />
										<br />
										<table cellspacing="0" cellpadding="0" border="0">
												<tbody>
														<tr>
																<td valign="center">
																		<img height="16" alt="" src="http://www.ibm.com/i/v14/icons/u_bold.gif" width="16" border="0" />
																		<br />
																</td>
																<td valign="top" align="right">
																		<a class="fbox" href="http://www-128.ibm.com/developerworks/cn/opensource/os-ecant/index.html#main">
																				<b>
																						<font face="Verdana" color="#996699">回页首</font>
																				</b>
																		</a>
																</td>
														</tr>
												</tbody>
										</table>
								</td>
						</tr>
				</tbody>
		</table>
		<br />
		<br />
		<p>
				<a name="N102D4">
						<span class="atitle">
								<font face="Arial" size="4">结束语</font>
						</span>
				</a>
		</p>
		<p>Eclipse 和 PyDev 插件的结合，以及 Apache Ant 与 Python Ant 任务一起使用，可以为 Python 开发提供完全集成的开发环境和构建/部署工具。这些工具尚在开发过程中，因此要经常查看是否有更新，如果您觉得特别希望看到某种特性，可以卷起袖管自力更生。 </p>
		<br />
		<table cellspacing="0" cellpadding="0" width="100%" border="0">
				<tbody>
						<tr>
								<td>
										<img height="1" alt="" src="http://www.ibm.com/i/v14/rules/blue_rule.gif" width="100%" />
										<br />
										<img height="6" alt="" src="http://www.ibm.com/i/c.gif" width="8" border="0" />
								</td>
						</tr>
				</tbody>
		</table>
		<table class="no-print" cellspacing="0" cellpadding="0" align="right">
				<tbody>
						<tr align="right">
								<td>
										<img height="4" alt="" src="http://www.ibm.com/i/c.gif" width="100%" />
										<br />
										<table cellspacing="0" cellpadding="0" border="0">
												<tbody>
														<tr>
																<td valign="center">
																		<img height="16" alt="" src="http://www.ibm.com/i/v14/icons/u_bold.gif" width="16" border="0" />
																		<br />
																</td>
																<td valign="top" align="right">
																		<a class="fbox" href="http://www-128.ibm.com/developerworks/cn/opensource/os-ecant/index.html#main">
																				<b>
																						<font face="Verdana" color="#996699">回页首</font>
																				</b>
																		</a>
																</td>
														</tr>
												</tbody>
										</table>
								</td>
						</tr>
				</tbody>
		</table>
		<br />
		<br />
		<p>
				<a name="resources">
						<span class="atitle">
								<font face="Arial" size="4">参考资料 </font>
						</span>
				</a>
		</p>
		<ul>
				<li>您可以参阅本文在 developerWorks 全球站点上的 <a href="http://www.ibm.com/developerworks/library/os-ecant/index.html"><font color="#5c81a7">英文原文</font></a>. <br /><br /></li>
				<li>下载本文的 <a href="ftp://www6.software.ibm.com/software/developer/library/os-ecant/feedparsertest.zip"><font color="#996699">样例程序与源代码</font></a>。 <br /><br /></li>
				<li>访问 <a href="http://www.eclipse.org/"><font color="#996699">Eclipse Web 站点</font></a>获取 Eclipse 下载文件和 Eclipse 文档。 <br /><br /></li>
				<li>
						<a href="http://eclipse-plugins.2y.net/">
								<font color="#5c81a7">Eclipse Plug-ins Web 站点</font>
						</a>中包含数以百计的商业和开放源代码插件，可供在 Eclipse 中安装。 <br /><br /></li>
				<li>
						<a href="http://ant.apache.org/">
								<font color="#5c81a7">Apache Ant Web 站点</font>
						</a>上有 Ant 下载和有关 Ant 的文档。 <br /><br /></li>
				<li>要获得 Python 的下载和相关信息，请参阅 <a href="http://python.org/"><font color="#5c81a7">Python Web 站点</font></a>。 <br /><br /></li>
				<li>
						<a href="http://pydev.sourceforge.net/">
								<font color="#5c81a7">PyDev SourceForge 项目站点</font>
						</a>提供了下载、文档和用户论坛。 <br /><br /></li>
				<li>
						<a href="http://www.rpstechnologies.net/PyAntTasks.html">
								<font color="#5c81a7">Python Ant tasks Web 站点</font>
						</a>包含最新版本的 Python Ant 任务。 <br /><br /></li>
				<li>Feed Parser 是用 Python 实现的通用资源解析器，可从 <a href="http://diveintomark.org/projects/feed_parser/"><font color="#5c81a7">Feed Parser Web 站点</font></a>上找到。 <br /><br /></li>
				<li>
						<a href="http://devworks.krcinfo.com/WebForms/ProductDetails.aspx?ProductID=0596001886">
								<font color="#5c81a7">
										<i>Python in a Nutshell</i>
								</font>
						</a>（O'Reilly &amp; Associates；2003），作者 Alex Martelli，是优秀的 Python 语言参考手册。 <br /><br /></li>
				<li>在 <i>developerWorks</i>的 <a href="http://www-128.ibm.com/developerworks/cn/opensource/"><font color="#5c81a7">开放源代码项目专区</font></a>中可以找到更多 <a href="http://www.ibm.com/developerworks/cn/views/opensource/articles.jsp"><font color="#5c81a7">为 Eclipse 用户撰写的文章</font></a>。也可以参看 <i>alphaWorks</i>上最新的 <a href="http://www.alphaworks.ibm.com/eclipse"><font color="#5c81a7">Eclipse 技术下载</font></a>。 <br /><br /></li>
				<li>在 Developer Bookstore 的开放源代码区中，可以找到数百本 <a href="http://devworks.krcinfo.com/WebForms/ProductList.aspx?Search=Category&amp;id=1400"><font color="#5c81a7">开放源代码打折书籍</font></a>，其中包括几本 <a href="http://devworks.krcinfo.com/WebForms/ProductList.aspx?search=FreeText&amp;SearchT=Keyword&amp;txtSearch=eclipse"><font color="#5c81a7">Eclipse</font></a>和 <a href="http://devworks.krcinfo.com/WebForms/ProductList.aspx?search=FreeText&amp;SearchT=Keyword&amp;txtSearch=struts&amp;SearchButton=GO"><font color="#5c81a7">Struts 应用程序开发</font></a> 方面的图书。 <br /><br /></li>
				<li>通过 <a href="http://www-128.ibm.com/developerworks/cn/subscription/" target="new"><font color="#5c81a7">developerWorks Subscription</font></a>用最新的 IBM 工具和中间件开发及测试您的应用程序；您可以获得包括基于 Eclipse 的 WebSphere、DB2、Lotus、Rational、Tivoli 在内的 IBM 软件，同时还有可使用 12 个月的软件许可，省钱超出您的想象。 <br /><br /></li>
				<li>下载 developerWorks Subscription 精选产品的免费试用版，这些产品可运行于 Linux 上，包括 WebSphere Studio Site Developer、WebSphere SDK for Web services、WebSphere Application Server、DB2 Universal Database Personal Developers Edition、Tivoli Access Manager 以及 Lotus Domino Server。下载链接在 developerWorks 的 <a href="http://www-128.ibm.com/developerworks/cn/linux/linux-speed-start/"><font color="#5c81a7">Speed-start your Linux app</font></a>区。想更快开始么？请自己访问产品使用文档和技术支持。 <br /></li>
		</ul>
		<br />
		<table cellspacing="0" cellpadding="0" width="100%" border="0">
				<tbody>
						<tr>
								<td>
										<img height="1" alt="" src="http://www.ibm.com/i/v14/rules/blue_rule.gif" width="100%" />
										<br />
										<img height="6" alt="" src="http://www.ibm.com/i/c.gif" width="8" border="0" />
								</td>
						</tr>
				</tbody>
		</table>
		<table class="no-print" cellspacing="0" cellpadding="0" align="right">
				<tbody>
						<tr align="right">
								<td>
										<img height="4" alt="" src="http://www.ibm.com/i/c.gif" width="100%" />
										<br />
										<table cellspacing="0" cellpadding="0" border="0">
												<tbody>
														<tr>
																<td valign="center">
																		<img height="16" alt="" src="http://www.ibm.com/i/v14/icons/u_bold.gif" width="16" border="0" />
																		<br />
																</td>
																<td valign="top" align="right">
																		<a class="fbox" href="http://www-128.ibm.com/developerworks/cn/opensource/os-ecant/index.html#main">
																				<b>
																						<font face="Verdana" color="#996699">回页首</font>
																				</b>
																		</a>
																</td>
														</tr>
												</tbody>
										</table>
								</td>
						</tr>
				</tbody>
		</table>
		<br />
		<br />
		<p>
				<a name="author">
						<span class="atitle">
								<font face="Arial" size="4">关于作者</font>
						</span>
				</a>
		</p>
		<table cellspacing="0" cellpadding="0" width="100%" border="0">
				<tbody>
						<tr>
								<td colspan="3">
										<font face="Arial" size="4">
												<img height="5" alt="" src="http://www.ibm.com/i/c.gif" width="100%" />
										</font>
								</td>
						</tr>
						<tr valign="top" align="left">
								<td>
										<p>
												<font face="Arial" size="4">
												</font>
										</p>
								</td>
								<td>
										<font face="Arial" size="4">
												<img height="5" alt="" src="http://www.ibm.com/i/c.gif" width="4" />
										</font>
								</td>
								<td width="100%">
										<p>Ron Smith 是 RPS Technologies, Inc 的创始人。这是一家软件开发与软件顾问公司，总部位于芝加哥地区。Ron Smith 为客户提供基于 J2EE 的企业应用程序发方面的咨询，同时也在 RPS Technologies 内部开发软件产品。可以通过 <a href="mailto:ron.smith@rpstechnologies.net"><font color="#5c81a7">ron.smith@rpstechnologies.net</font></a>与 Ron 联系。 </p>
								</td>
						</tr>
				</tbody>
		</table>
<img src ="http://www.cppblog.com/Jeff-Chen/aggbug/5521.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.cppblog.com/Jeff-Chen/" target="_blank">Jeff-Chen</a> 2006-04-14 11:34 <a href="http://www.cppblog.com/Jeff-Chen/archive/2006/04/14/5521.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item><item><title>Python 学习之路（四）</title><link>http://www.cppblog.com/Jeff-Chen/archive/2006/04/13/5494.html</link><dc:creator>Jeff-Chen</dc:creator><author>Jeff-Chen</author><pubDate>Thu, 13 Apr 2006 13:49:00 GMT</pubDate><guid>http://www.cppblog.com/Jeff-Chen/archive/2006/04/13/5494.html</guid><wfw:comment>http://www.cppblog.com/Jeff-Chen/comments/5494.html</wfw:comment><comments>http://www.cppblog.com/Jeff-Chen/archive/2006/04/13/5494.html#Feedback</comments><slash:comments>0</slash:comments><wfw:commentRss>http://www.cppblog.com/Jeff-Chen/comments/commentRss/5494.html</wfw:commentRss><trackback:ping>http://www.cppblog.com/Jeff-Chen/services/trackbacks/5494.html</trackback:ping><description><![CDATA[
		<p>
				<a name="c40ab4c10b2">
						<font face="Arial" size="2">
						</font>
				</a>
				<b>
				</b>
		</p>
		<p>
				<font face="Arial">
						<font size="2">
								<strong>Note One：about sequences and lists<br /></strong>
								<br />序列是不可变列表。一旦创建了一个序列就不能以任何方式改变它。</font>
				</font>
		</p>
		<p>
				<a name="c40ab4c10b3">
				</a>
				<b>
						<font face="Arial" size="2">例 1.21. 定义序列<br /></font>
				</b>
				<font face="Arial">
						<font size="2">
								<tt>
										<br />&gt;&gt;&gt; </tt>
								<span class="userinput">t = (<tt class="string">"a"</tt>, <tt class="string">"b"</tt>, <tt class="string">"mpilgrim"</tt>, <tt class="string">"z"</tt>, <tt class="string">"example"</tt>)</span>
						</font>
				</font>
				<a name="odbchelper.tuple.1.1">
				</a>
				<font face="Arial" size="2">
						<img height="12" alt="1" src="http://cn.diveintopython.org/images/callouts/1.jpg" width="12" border="0" />
						<br />
						<tt>&gt;&gt;&gt; </tt>
						<span class="userinput">t</span>
						<br />
						<span class="computeroutput">('a', 'b', 'mpilgrim', 'z', 'example')</span>
						<br />
						<tt>&gt;&gt;&gt; </tt>
						<span class="userinput">t[0]</span>
				</font>
				<a name="odbchelper.tuple.1.2">
				</a>
				<font face="Arial" size="2">
						<img height="12" alt="2" src="http://cn.diveintopython.org/images/callouts/2.jpg" width="12" border="0" />
						<br />
						<span class="computeroutput">'a'</span>
						<br />
						<tt>&gt;&gt;&gt; </tt>
						<span class="userinput">t[-1]</span>                                      </font>
				<a name="odbchelper.tuple.1.3">
				</a>
				<font face="Arial" size="2">
						<img height="12" alt="3" src="http://cn.diveintopython.org/images/callouts/3.jpg" width="12" border="0" />
						<br />
						<span class="computeroutput">'example'</span>
						<br />
						<tt>&gt;&gt;&gt; </tt>
						<span class="userinput">t[1:3]</span>                                     </font>
				<a name="odbchelper.tuple.1.4">
				</a>
				<font face="Arial">
						<font size="2">
								<img height="12" alt="4" src="http://cn.diveintopython.org/images/callouts/4.jpg" width="12" border="0" />
								<br />
								<span class="computeroutput">('b', 'mpilgrim')</span>
						</font>
				</font>
		</p>
		<table summary="Callout list" border="0">
				<tbody>
						<tr>
								<td valign="top" align="left" width="12">
										<a href="http://cn.diveintopython.org/odbchelper_tuple.html#odbchelper.tuple.1.1">
												<font face="Arial" size="2">
														<img height="12" alt="1" src="http://cn.diveintopython.org/images/callouts/1.jpg" width="12" border="0" />
												</font>
										</a>
										<font face="Arial" size="2">
										</font>
								</td>
								<td valign="top" align="left">
										<font face="Arial" color="#ff0000" size="2">序列的定义同列表的定义方式相同，除了整个元素集是用小括号包围的而不是方括号。</font>
								</td>
						</tr>
						<tr>
								<td valign="top" align="left" width="12">
										<a href="http://cn.diveintopython.org/odbchelper_tuple.html#odbchelper.tuple.1.2">
												<font face="Arial" size="2">
														<img height="12" alt="2" src="http://cn.diveintopython.org/images/callouts/2.jpg" width="12" border="0" />
												</font>
										</a>
										<font face="Arial" size="2">
										</font>
								</td>
								<td valign="top" align="left">
										<font face="Arial" size="2">序列的元素象列表一样按定义的次序进行排序。序列的索引象列表一样从0开始，所以一个非空序列的第一个元素总是<tt> t[0]</tt>。</font>
								</td>
						</tr>
						<tr>
								<td valign="top" align="left" width="12">
										<a href="http://cn.diveintopython.org/odbchelper_tuple.html#odbchelper.tuple.1.3">
												<font face="Arial" size="2">
														<img height="12" alt="3" src="http://cn.diveintopython.org/images/callouts/3.jpg" width="12" border="0" />
												</font>
										</a>
										<font face="Arial" size="2">
										</font>
								</td>
								<td valign="top" align="left">
										<font face="Arial" size="2">负数索引象列表一样从序列尾部开始计数。</font>
								</td>
						</tr>
						<tr>
								<td valign="top" align="left" width="12">
										<a href="http://cn.diveintopython.org/odbchelper_tuple.html#odbchelper.tuple.1.4">
												<font face="Arial" size="2">
														<img height="12" alt="4" src="http://cn.diveintopython.org/images/callouts/4.jpg" width="12" border="0" />
												</font>
										</a>
										<font face="Arial" size="2">
										</font>
								</td>
								<td valign="top" align="left">
										<font face="Arial" size="2">分片也可以使用，就象列表一样。注意当分割一个列表时，会得到一个新的列表；当分割一个序列时，会得到一个新的序列。</font>
								</td>
						</tr>
				</tbody>
		</table>
		<p>
				<a name="odbchelper.tuplemethods">
				</a>
				<b>
						<font face="Arial" size="2">例 1.22. 序列没有方法</font> <br /></b>
				<font face="Arial">
						<font size="2">
								<br />
								<tt>&gt;&gt;&gt; </tt>
								<span class="userinput">t</span>
								<br />
								<span class="computeroutput">('a', 'b', 'mpilgrim', 'z', 'example')</span>
								<br />
								<tt>&gt;&gt;&gt; </tt>
								<span class="userinput">t.append(<tt class="string">"new"</tt>)</span> </font> <br /></font>
				<font face="Arial">
						<font size="2">
								<span class="traceback">Traceback (innermost last):<br />File "&lt;interactive input&gt;", line 1, in ?<br />AttributeError: 'tuple' object has no attribute 'append'</span>
								<br />
								<tt>&gt;&gt;&gt; </tt>
								<span class="userinput">t.remove(<tt class="string">"z"</tt>)</span>  </font>
				</font>
				<font face="Arial" size="2">         </font>    <br /><font face="Arial"><font size="2"><span class="traceback">Traceback (innermost last):<br />File "&lt;interactive input&gt;", line 1, in ?<br />AttributeError: 'tuple' object has no attribute 'remove'</span><br /><tt>&gt;&gt;&gt; </tt><span class="userinput">t.index(<tt class="string">"example"</tt>)</span>  <br /></font></font><font face="Arial"><font size="2"><span class="traceback">Traceback (innermost last):<br />  File "&lt;interactive input&gt;", line 1, in ?<br />AttributeError: 'tuple' object has no attribute 'index'</span><br /><tt>&gt;&gt;&gt;</tt><span class="userinput"><tt class="string">"z"</tt> <tt class="keyword">in</tt> t</span>  <br /></font></font><font face="Arial"><font size="2"><span class="computeroutput">1</span>   </font></font></p>
		<table summary="Callout list" border="0">
				<tbody>
						<tr>
								<td valign="top" align="left" width="12">
										<a href="http://cn.diveintopython.org/odbchelper_tuple.html#odbchelper.tuple.2.1">
												<font face="Arial" size="2">
														<img height="12" alt="1" src="http://cn.diveintopython.org/images/callouts/1.jpg" width="12" border="0" />
												</font>
										</a>
										<font face="Arial" size="2">
										</font>
								</td>
								<td valign="top" align="left">
										<font face="Arial" color="#ff0000" size="2">你不能向序列增加元素。序列没有 <font face="Arial"><tt>append</tt> 或 </font><tt>extend</tt> 方法。</font>
								</td>
						</tr>
						<tr>
								<td valign="top" align="left" width="12">
										<a href="http://cn.diveintopython.org/odbchelper_tuple.html#odbchelper.tuple.2.2">
												<font face="Arial" color="#ff0000" size="2">
														<img height="12" alt="2" src="http://cn.diveintopython.org/images/callouts/2.jpg" width="12" border="0" />
												</font>
										</a>
										<font face="Arial" color="#ff0000" size="2">
										</font>
								</td>
								<td valign="top" align="left">
										<font face="Arial" color="#ff0000" size="2">你不能从序列中除掉元素。序列没有 <tt>remove</tt> 或<tt> pop</tt> 方法。</font>
								</td>
						</tr>
						<tr>
								<td valign="top" align="left" width="12">
										<a href="http://cn.diveintopython.org/odbchelper_tuple.html#odbchelper.tuple.2.3">
												<font face="Arial" color="#ff0000" size="2">
														<img height="12" alt="3" src="http://cn.diveintopython.org/images/callouts/3.jpg" width="12" border="0" />
												</font>
										</a>
										<font face="Arial" color="#ff0000" size="2">
										</font>
								</td>
								<td valign="top" align="left">
										<font face="Arial" color="#ff0000" size="2">你不能在序列中查找元素。序列没有 <tt>index</tt> 方法。</font>
								</td>
						</tr>
						<tr>
								<td valign="top" align="left" width="12">
										<a href="http://cn.diveintopython.org/odbchelper_tuple.html#odbchelper.tuple.2.4">
												<font face="Arial" color="#ff0000" size="2">
														<img height="12" alt="4" src="http://cn.diveintopython.org/images/callouts/4.jpg" width="12" border="0" />
												</font>
										</a>
										<font face="Arial" color="#ff0000" size="2">
										</font>
								</td>
								<td valign="top" align="left">
										<font face="Arial" size="2">
												<font color="#ff0000">然而，你可以使用 <tt>in</tt> 来看一看是否一个元素存在于序列中</font>。</font>
								</td>
						</tr>
				</tbody>
		</table>
		<p>
				<font face="Arial" size="2">那么序列有什么好处呢？</font>
		</p>
		<ul>
				<li>
						<font face="Arial" size="2">
								<font color="#ff0000">序列比列表操作速度快。如果你定义了一个值集合常量，并且唯一要用它做的是不断地遍历它，使用序列代替列表。</font>
						</font>
				</li>
				<li>
						<font face="Arial" size="2">记得我说过</font>
						<a title="Example 1.11. Mixing datatypes in a dictionary" href="http://cn.diveintopython.org/odbchelper_dict.html#odbchelper.dictionarytypes">
								<font face="Arial" size="2">字典关键字</font>
						</a>
						<font face="Arial" size="2">可以是整数，字符串和“几种其它的类型”吗？序列就是那些类型之一。序列可以在字典中被用作关键字，但是列表不行。<sup>[<a href="http://cn.diveintopython.org/odbchelper_tuple.html#ftn.c40ab4c10b6b1ab5" name="c40ab4c10b6b1ab5">2</a>]</sup></font>
				</li>
				<li>
						<font face="Arial" size="2">序列用在字符串格式化，这一点我们会很快看到。 </font>
				</li>
		</ul>
		<p align="left">
				<font size="2">
						<font face="Arial">
								<strong>Note Two : Mapping in the Lists</strong>
								<br />
								<br />
								<strong>列表映射介绍</strong> </font>
				</font>    <font size="2"><font face="Arial">  <br /><tt>&gt;&gt;&gt; </tt> <span class="userinput">li = [1, 9, 8, 4]</span><br /><tt>&gt;&gt;&gt; </tt> <span class="userinput">[elem*2 <tt class="keyword">for</tt> elem <tt class="keyword">in</tt> li]</span></font></font><font face="Arial" size="2">      <img height="12" alt="1" src="http://cn.diveintopython.org/images/callouts/1.jpg" width="12" border="0" /><br /><span class="computeroutput">[2, 18, 16, 8]</span><br /><tt>&gt;&gt;&gt; </tt> <span class="userinput">li                     </span></font><font size="2"><font face="Arial"><img height="12" alt="2" src="http://cn.diveintopython.org/images/callouts/2.jpg" width="12" border="0" /><br /><span class="computeroutput">[1, 9, 8, 4]</span></font></font></p>
		<p>
		</p>
		<table summary="Callout list" border="0">
				<tbody>
						<tr>
								<td valign="top" align="left" width="12">
										<a href="http://cn.diveintopython.org/odbchelper_map.html#odbchelper.map.1.1">
												<font face="Arial" size="2">
														<img height="12" alt="1" src="http://cn.diveintopython.org/images/callouts/1.jpg" width="12" border="0" />
												</font>
										</a>
										<font face="Arial" size="2">
										</font>
								</td>
								<td valign="top" align="left">
										<p>
												<font face="Arial" size="2">为了对这一点有一个感性认识，从右向左看它。 <tt>li</tt> 是一个将要映射的列表。Python循环遍历 <tt>li</tt> 一次一个元素，临时将每个元素的值赋给变量 <tt>elem</tt>。然后Python使用函数 <tt><tt>elem</tt>*2</tt> ，接着将结果追加到返回列表中。</font>
										</p>
								</td>
						</tr>
						<tr>
								<td valign="top" align="left" width="12">
										<a href="http://cn.diveintopython.org/odbchelper_map.html#odbchelper.map.1.2">
												<font face="Arial" size="2">
														<img height="12" alt="2" src="http://cn.diveintopython.org/images/callouts/2.jpg" width="12" border="0" />
												</font>
										</a>
										<font face="Arial" color="#a52a2a" size="2">
										</font>
								</td>
								<td valign="top" align="left">
										<font face="Arial" color="#a52a2a" size="2">注<font color="#ff0000">意列表映射不改变被映射的列表。</font></font>
								</td>
						</tr>
				</tbody>
		</table>
		<br />
		<font face="Arial" size="2">
				<strong>Note Three :好东西 lambda 函数</strong>
		</font>
		<p>
				<a name="c40ab5b9b2">
				</a>
				<b>
				</b>
		</p>
		<p>
				<font face="Arial" size="2">Python支持一种有趣的语法，它允许你快速定义单行的最小函数。这些叫做 <tt>lambda</tt> 的函数是从Lisp中借用来的，可以被用在任何需要函数的地方。</font>
		</p>
		<p>
				<font face="Arial" size="2">出于历史的原因，<tt>lambda</tt> 函数的语法与通常的函数有些细微的不同。</font>
		</p>
		<p>
				<a name="c40ab5b9b4">
				</a>
				<b>
						<font face="Arial" size="2">例 2.20. <tt>lambda</tt> 函数介绍<br /></font>
				</b>
				<font face="Arial">
						<font size="2">
								<tt>&gt;&gt;&gt; </tt>
								<span class="userinput">
										<tt class="keyword">def</tt>
										<tt class="function">f</tt>(x):</span>          </font>
				</font>
				<a name="apihelper.lambda.1.1">
				</a>
				<font face="Arial" size="2">
						<img height="12" alt="1" src="http://cn.diveintopython.org/images/callouts/1.jpg" width="12" border="0" />
						<br />
						<tt>...     </tt>
						<span class="userinput">
								<tt class="keyword">return</tt> x*2</span>
						<br />
						<tt>...     </tt>
						<span class="userinput">
						</span>
						<br />
						<tt>&gt;&gt;&gt; </tt>
						<span class="userinput">f(3)</span>
						<br />
						<span class="computeroutput">6</span>
						<br />
						<tt>&gt;&gt;&gt; </tt>
						<span class="userinput">g = <tt class="keyword">lambda</tt> x: x*2</span>  </font>
				<a name="apihelper.lambda.1.2">
				</a>
				<font face="Arial" size="2">
						<img height="12" alt="2" src="http://cn.diveintopython.org/images/callouts/2.jpg" width="12" border="0" />
						<br />
						<tt>&gt;&gt;&gt; </tt>
						<span class="userinput">g(3)</span>
						<br />
						<span class="computeroutput">6</span>
						<br />
						<tt>&gt;&gt;&gt; </tt>
						<span class="userinput">
								<tt class="keyword">(lambda</tt> x: x*2)(3)</span>
				</font>
				<a name="apihelper.lambda.1.3">
				</a>
				<font face="Arial">
						<font size="2">
								<img height="12" alt="3" src="http://cn.diveintopython.org/images/callouts/3.jpg" width="12" border="0" />
								<br />
								<span class="computeroutput">6</span>
						</font>
				</font>
		</p>
		<table summary="Callout list" border="0">
				<tbody>
						<tr>
								<td valign="top" align="left" width="12">
										<a href="http://cn.diveintopython.org/apihelper_lambda.html#apihelper.lambda.1.1">
												<font face="Arial" size="2">
														<img height="12" alt="1" src="http://cn.diveintopython.org/images/callouts/1.jpg" width="12" border="0" />
												</font>
										</a>
										<font face="Arial" size="2">
										</font>
								</td>
								<td valign="top" align="left">
										<p>
												<font face="Arial" size="2">这是一个通常的函数声明，尽管以前你可能没有看到过定义在交互式窗口中的函数。这个 ... 说明它是一个多行的交互语句。只要在第一行的后面敲入回车，Python IDE会让你接着输入命令。</font>
										</p>
								</td>
						</tr>
						<tr>
								<td valign="top" align="left" width="12">
										<a href="http://cn.diveintopython.org/apihelper_lambda.html#apihelper.lambda.1.2">
												<font face="Arial" size="2">
														<img height="12" alt="2" src="http://cn.diveintopython.org/images/callouts/2.jpg" width="12" border="0" />
												</font>
										</a>
										<font face="Arial" size="2">
										</font>
								</td>
								<td valign="top" align="left">
										<p>
												<font face="Arial" size="2">这是一个 <tt>lambda</tt> 函数，它完成同上面普通函数相同的事情。注意这里的简短的语法；没有小括号， <tt>return</tt> 是默认的，并且函数没有名字，只有将它赋值给变量的变量名。</font>
										</p>
								</td>
						</tr>
						<tr>
								<td valign="top" align="left" width="12">
										<a href="http://cn.diveintopython.org/apihelper_lambda.html#apihelper.lambda.1.3">
												<font face="Arial" size="2">
														<img height="12" alt="3" src="http://cn.diveintopython.org/images/callouts/3.jpg" width="12" border="0" />
												</font>
										</a>
										<font face="Arial" size="2">
										</font>
								</td>
								<td valign="top" align="left">
										<p>
												<font face="Arial" size="2">你甚至可以不将 <tt>lambda</tt> 函数赋值给一个变量而使用它。这不是举世无双的东西，它只是展示了 lambda 函数只是一个内联函数。</font>
										</p>
								</td>
						</tr>
				</tbody>
		</table>
		<p>
				<font face="Arial" size="2">总之， <tt>lambda</tt> 函数是一个可以接收任意多个参数(包括</font>
				<a title="2.3. Optional and named arguments" href="http://cn.diveintopython.org/apihelper_optional.html">
						<font face="Arial" size="2">可选参数</font>
				</a>
				<font face="Arial" size="2">)并且返回单个表达式值的函数。 <tt>lambda</tt> 函数不能包含命令，它们所包含的表达式不能超过一个。不要试图向 <tt>lambda</tt> 函数中塞入太多的东西；如果你需要更复杂的东西，应该定义一个普通函数，然后想让它多长就多长。</font>
		</p>
		<p>
				<a name="tip.lambda">
						<font face="Arial" size="2">
						</font>
				</a>
		</p>
		<table class="note" border="0">
				<tbody>
						<tr>
								<td valign="top" align="middle" width="25" rowspan="2">
										<font face="Arial" size="2">
												<img height="25" alt="Note" src="http://cn.diveintopython.org/images/note.jpg" width="25" />
										</font>
								</td>
						</tr>
						<tr>
								<td valign="top" align="left" colspan="2">
										<font face="Arial">
												<font size="2">
														<tt>lambda</tt> 函数是风格问题。不一定非要使用它们，任何能够使用它们的地方，都可以定义一个分离的普通的函数，用它来替换。我将它们用在需要封装特殊的，非重用的代码上，用许多小的一行函数不会弄乱我的代码。</font>
										</font>
								</td>
						</tr>
				</tbody>
		</table>
		<p>
				<a name="c40ab5b9b7">
				</a>
				<b>
						<font face="Arial" size="2">例 2.21. 在 in <tt>apihelper.py</tt> 中的 <tt>lambda</tt> 函数</font> <br /></b>
				<font face="Arial" size="2">processFunc = collapse <tt class="keyword">and</tt> (<tt class="keyword">lambda</tt> s: <tt class="string">" "</tt>.join(s.split())) <tt class="keyword">or</tt> (<tt class="keyword">lambda</tt> s: s)</font>
				<br />
		</p>
		<p>
				<font face="Arial" size="2">顺便这里有几件事情需要注意。首先，我们使用了 </font>
				<a title="2.7. The and-or trick" href="http://cn.diveintopython.org/apihelper_andor.html">
						<tt>
								<font face="Arial" size="2">and-or</font>
						</tt>
				</a>
				<font face="Arial" size="2">技巧的简单形式，没问题，因为一个 <tt>lambda</tt> 函数</font>
				<a title="Note:  What's true in Python?" href="http://cn.diveintopython.org/odbchelper_list.html#tip.boolean">
						<font face="Arial" size="2">在一个布尔环境下</font>
				</a>
				<font face="Arial" size="2">总为真。(这并不意味着 <tt>lambda</tt> 函数不能返回假值。函数本身总是为真，它的返回值可以为任何值。)</font>
		</p>
		<p>
				<font face="Arial" size="2">第二，我们使用了 <tt>split</tt> 函数没带参数。你已经看到过它带</font>
				<a title="Example 1.34. Splitting a string" href="http://cn.diveintopython.org/odbchelper_join.html#odbchelper.split.example">
						<font face="Arial" size="2">1个或2个参数</font>
				</a>
				<font face="Arial" size="2">的使用，但是不带参数它按空白进行分割。</font>
		</p>
		<p>
				<a name="c40ab5b9c10">
				</a>
				<b>
						<font face="Arial" size="2">例 2.22. <tt>split</tt> 不带参数</font> </b>   <br /><font face="Arial"><font size="2"><tt>&gt;&gt;&gt;</tt><span class="userinput">s = <tt class="string">"this   is\na\ttest"</tt></span>    </font></font><font face="Arial" size="2">     <img height="12" alt="1" src="http://cn.diveintopython.org/images/callouts/1.jpg" width="12" border="0" /><br /><tt>&gt;&gt;&gt;</tt><span class="userinput"><tt class="keyword">print</tt> s</span></font>  <br /><font face="Arial"><font size="2"> <span class="computeroutput">this   is<br />a test</span><br /><tt>&gt;&gt;&gt;</tt><span class="userinput"><tt class="keyword">print</tt> s.split()</span></font></font><font face="Arial" size="2">      <img height="12" alt="2" src="http://cn.diveintopython.org/images/callouts/2.jpg" width="12" border="0" /><br /><span class="computeroutput">['this', 'is', 'a', 'test']</span><br /><tt>&gt;&gt;&gt;</tt><span class="userinput"><tt class="keyword">print</tt>   <tt class="string">" "</tt>.join(s.split())</span></font><font face="Arial"><font size="2">        <img height="12" alt="3" src="http://cn.diveintopython.org/images/callouts/3.jpg" width="12" border="0" /><br /><span class="computeroutput">'this is a test'</span>    </font></font></p>
		<table summary="Callout list" border="0">
				<tbody>
						<tr>
								<td valign="top" align="left" width="12">
										<a href="http://cn.diveintopython.org/apihelper_lambda.html#apihelper.split.1.1">
												<font face="Arial" size="2">
														<img height="12" alt="1" src="http://cn.diveintopython.org/images/callouts/1.jpg" width="12" border="0" />
												</font>
										</a>
										<font face="Arial" size="2">
										</font>
								</td>
								<td valign="top" align="left">
										<p>
												<font face="Arial" size="2">这是一个多行字符串，通过转义字符的定义代替了</font>
												<a title="Example 1.4. Defining the buildConnectionString function's doc string" href="http://cn.diveintopython.org/odbchelper_docstring.html#odbchelper.triplequotes">
														<font face="Arial" size="2">三重引号</font>
												</a>
												<font face="Arial" size="2">。 <tt>\n</tt> 是一个回车； <tt>\t</tt> 是一个制表符。</font>
										</p>
								</td>
						</tr>
						<tr>
								<td valign="top" align="left" width="12">
										<a href="http://cn.diveintopython.org/apihelper_lambda.html#apihelper.split.1.2">
												<font face="Arial" size="2">
														<img height="12" alt="2" src="http://cn.diveintopython.org/images/callouts/2.jpg" width="12" border="0" />
												</font>
										</a>
										<font face="Arial" size="2">
										</font>
								</td>
								<td valign="top" align="left">
										<p>
												<font face="Arial">
														<font size="2">
																<tt>split</tt> 不带参数按空白进行分割。所以三个空格，一个回车，和一个制表符都是一样的。</font>
												</font>
										</p>
								</td>
						</tr>
						<tr>
								<td valign="top" align="left" width="12">
										<a href="http://cn.diveintopython.org/apihelper_lambda.html#apihelper.split.1.3">
												<font face="Arial" size="2">
														<img height="12" alt="3" src="http://cn.diveintopython.org/images/callouts/3.jpg" width="12" border="0" />
												</font>
										</a>
										<font face="Arial" size="2">
										</font>
								</td>
								<td valign="top" align="left">
										<p>
												<font face="Arial" size="2">你可以将空白统一化，通过分割一个字符串，然后用单个空格作为分隔符将其重新接起来。这就是 <tt>help</tt> 函数所做的，将多行文档字符串合并成单行。</font>
										</p>
								</td>
						</tr>
				</tbody>
		</table>
		<p>
				<font face="Arial" size="2">那么 <tt>help</tt> 函数到底用这些 <tt>lambda</tt> 函数， <tt>split</tt> 函数，和 <tt>and-or</tt> 技巧做了什么呢？ </font>
		</p>
		<p>
				<a name="apihelper.funcassign">
				</a>
				<b>
						<font face="Arial" size="2">例 2.23. 将函数赋给一个变量</font>
				</b>
		</p>
		<pre>
				<font face="Arial" size="2"> processFunc = collapse <tt class="keyword">and</tt> (<tt class="keyword">lambda</tt> s: <tt class="string">" "</tt>.join(s.split())) <tt class="keyword">or</tt> (<tt class="keyword">lambda</tt> s: s)</font>
		</pre>
		<p>
				<font face="Arial">
						<font size="2">
								<tt>processFunc</tt> 现在是一个函数，但它为哪一个函数要看 <tt>collapse</tt> 变量的值。如果 <tt>collapse</tt> 为真， <tt><tt>processFunc</tt>(<i>string</i>)</tt> 将压缩空白；否则，<tt><tt>processFunc</tt>(<i>string</i>)</tt> 将返回未改变的参数。 </font>
				</font>
		</p>
		<p>
				<font face="Arial" size="2">在一个不很建壮的语言实现它，象VB，你将可能创建一个函数，它接收一个字符串和一个 <i><tt>collapse</tt></i> 参数，使用一个 <tt>if</tt> 语句来判断是否要压缩空白或不压缩，然后返回相应的值。这样效率低，因为函数将不得不处理每种可能性；每次你调用它，它将不得不在给出你所想要的东西之前，判断是否要压缩空白。在Python中，你可以将那种判断逻辑拿到函数外面，而定义一个裁减过的 <tt>lambda</tt> 函数来给出确切的(并且唯一)你想要的。这样做更有效率，更漂亮，并且更少导致那些令人讨厌的(哦，想到那些参数就头昏)的错误。<br /></font>
		</p>
<img src ="http://www.cppblog.com/Jeff-Chen/aggbug/5494.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.cppblog.com/Jeff-Chen/" target="_blank">Jeff-Chen</a> 2006-04-13 21:49 <a href="http://www.cppblog.com/Jeff-Chen/archive/2006/04/13/5494.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item><item><title>Python 学习之路（Brief Outlook of Library:Two）</title><link>http://www.cppblog.com/Jeff-Chen/archive/2006/04/13/5484.html</link><dc:creator>Jeff-Chen</dc:creator><author>Jeff-Chen</author><pubDate>Thu, 13 Apr 2006 11:45:00 GMT</pubDate><guid>http://www.cppblog.com/Jeff-Chen/archive/2006/04/13/5484.html</guid><wfw:comment>http://www.cppblog.com/Jeff-Chen/comments/5484.html</wfw:comment><comments>http://www.cppblog.com/Jeff-Chen/archive/2006/04/13/5484.html#Feedback</comments><slash:comments>0</slash:comments><wfw:commentRss>http://www.cppblog.com/Jeff-Chen/comments/commentRss/5484.html</wfw:commentRss><trackback:ping>http://www.cppblog.com/Jeff-Chen/services/trackbacks/5484.html</trackback:ping><description><![CDATA[
		<a name="CHILD_LINKS">
				<font face="Tahoma">
						<font size="2">
								<strong>Subsections</strong>
						</font>
				</font>
		</a>
		<ul class="ChildLinks">
				<li>
						<a href="http://www.python.org/doc/tut/node13.html#SECTION0013100000000000000000">
								<font face="Tahoma">
										<font size="2">
												<font color="#002c99">11.1 Output Formatting</font>
										</font>
								</font>
						</a>
				</li>
				<li>
						<a href="http://www.python.org/doc/tut/node13.html#SECTION0013200000000000000000">
								<font face="Tahoma">
										<font size="2">
												<font color="#002c99">11.2 Templating</font>
										</font>
								</font>
						</a>
				</li>
				<li>
						<a href="http://www.python.org/doc/tut/node13.html#SECTION0013300000000000000000">
								<font face="Tahoma">
										<font size="2">
												<font color="#002c99">11.3 Working with Binary Data Record Layouts</font>
										</font>
								</font>
						</a>
				</li>
				<li>
						<a href="http://www.python.org/doc/tut/node13.html#SECTION0013400000000000000000">
								<font face="Tahoma">
										<font size="2">
												<font color="#002c99">11.4 Multi-threading</font>
										</font>
								</font>
						</a>
				</li>
				<li>
						<a href="http://www.python.org/doc/tut/node13.html#SECTION0013500000000000000000">
								<font face="Tahoma">
										<font size="2">
												<font color="#002c99">11.5 Logging</font>
										</font>
								</font>
						</a>
				</li>
				<li>
						<a href="http://www.python.org/doc/tut/node13.html#SECTION0013600000000000000000">
								<font face="Tahoma">
										<font size="2">
												<font color="#002c99">11.6 Weak References</font>
										</font>
								</font>
						</a>
				</li>
				<li>
						<a href="http://www.python.org/doc/tut/node13.html#SECTION0013700000000000000000">
								<font face="Tahoma">
										<font size="2">
												<font color="#002c99">11.7 Tools for Working with Lists</font>
										</font>
								</font>
						</a>
				</li>
				<li>
						<a href="http://www.python.org/doc/tut/node13.html#SECTION0013800000000000000000">
								<font face="Tahoma">
										<font size="2">
												<font color="#002c99">11.8 Decimal Floating Point Arithmetic</font>
										</font>
								</font>
						</a>
				</li>
		</ul>
		<!--End of Table of Child-Links-->
		<font face="Tahoma" size="2">
				<hr />
		</font>
		<h1>
				<a name="SECTION0013000000000000000000">
				</a>
				<a name="briefTourTwo">
				</a>
				<br />
				<font face="Tahoma" size="2">11. Brief Tour of the Standard Library - Part II </font>
		</h1>
		<p>
				<font face="Tahoma" size="2">This second tour covers more advanced modules that support professional programming needs. These modules rarely occur in small scripts. </font>
		</p>
		<p>
				<font face="Tahoma" size="2">
				</font>
		</p>
		<h1>
				<a name="SECTION0013100000000000000000">
				</a>
				<a name="output-formatting">
				</a>
				<br />
				<font face="Tahoma" size="2">11.1 Output Formatting </font>
		</h1>
		<p>
				<font face="Tahoma" size="2">The </font>
				<a class="ulink" href="http://www.python.org/doc/lib/module-repr.html">
						<tt class="module">
								<font face="Tahoma">
										<font size="2">
												<font color="#002c99">repr</font>
										</font>
								</font>
						</tt>
				</a>
				<font face="Tahoma" size="2">module provides an version of <tt class="function">repr()</tt> for abbreviated displays of large or deeply nested containers: </font>
		</p>
		<p>
				<font face="Tahoma" size="2">
				</font>
		</p>
		<div class="verbatim">
				<pre>
						<font face="Tahoma" size="2">												    &gt;&gt;&gt; import repr   
    &gt;&gt;&gt; repr.repr(set('supercalifragilisticexpialidocious'))
    "set(['a', 'c', 'd', 'e', 'f', 'g', ...])"

				
				</font>
				</pre>
		</div>
		<p>
				<font face="Tahoma" size="2">The </font>
				<a class="ulink" href="http://www.python.org/doc/lib/module-pprint.html">
						<tt class="module">
								<font face="Tahoma">
										<font size="2">
												<font color="#002c99">pprint</font>
										</font>
								</font>
						</tt>
				</a>
				<font face="Tahoma" size="2">module offers more sophisticated control over printing both built-in and user defined objects in a way that is readable by the interpreter. When the result is longer than one line, the ``pretty printer'' adds line breaks and indentation to more clearly reveal data structure: </font>
		</p>
		<p>
				<font face="Tahoma" size="2">
				</font>
		</p>
		<div class="verbatim">
				<pre>
						<font face="Tahoma" size="2">												    &gt;&gt;&gt; import pprint
    &gt;&gt;&gt; t = [[[['black', 'cyan'], 'white', ['green', 'red']], [['magenta',
    ...     'yellow'], 'blue']]]
    ...
    &gt;&gt;&gt; pprint.pprint(t, width=30)
    [[[['black', 'cyan'],
       'white',
       ['green', 'red']],
      [['magenta', 'yellow'],
       'blue']]]

				
				</font>
				</pre>
		</div>
		<p>
				<font face="Tahoma" size="2">The </font>
				<a class="ulink" href="http://www.python.org/doc/lib/module-textwrap.html">
						<tt class="module">
								<font face="Tahoma">
										<font size="2">
												<font color="#002c99">textwrap</font>
										</font>
								</font>
						</tt>
				</a>
				<font face="Tahoma" size="2">module formats paragraphs of text to fit a given screen width: </font>
		</p>
		<p>
				<font face="Tahoma" size="2">
				</font>
		</p>
		<div class="verbatim">
				<pre>
						<font face="Tahoma" size="2">												    &gt;&gt;&gt; import textwrap
    &gt;&gt;&gt; doc = """The wrap() method is just like fill() except that it returns
    ... a list of strings instead of one big string with newlines to separate
    ... the wrapped lines."""
    ...
    &gt;&gt;&gt; print textwrap.fill(doc, width=40)
    The wrap() method is just like fill()
    except that it returns a list of strings
    instead of one big string with newlines
    to separate the wrapped lines.

				
				</font>
				</pre>
		</div>
		<p>
				<font face="Tahoma" size="2">The </font>
				<a class="ulink" href="http://www.python.org/doc/lib/module-locale.html">
						<tt class="module">
								<font face="Tahoma">
										<font size="2">
												<font color="#002c99">locale</font>
										</font>
								</font>
						</tt>
				</a>
				<font face="Tahoma" size="2">module accesses a database of culture specific data formats. The grouping attribute of locale's format function provides a direct way of formatting numbers with group separators: </font>
		</p>
		<p>
				<font face="Tahoma" size="2">
				</font>
		</p>
		<div class="verbatim">
				<pre>
						<font face="Tahoma" size="2">												    &gt;&gt;&gt; import locale
    &gt;&gt;&gt; locale.setlocale(locale.LC_ALL, 'English_United States.1252')
    'English_United States.1252'
    &gt;&gt;&gt; conv = locale.localeconv()          # get a mapping of conventions
    &gt;&gt;&gt; x = 1234567.8
    &gt;&gt;&gt; locale.format("%d", x, grouping=True)
    '1,234,567'
    &gt;&gt;&gt; locale.format("%s%.*f", (conv['currency_symbol'],
    ...	      conv['frac_digits'], x), grouping=True)
    '$1,234,567.80'

				
				</font>
				</pre>
		</div>
		<p>
				<font face="Tahoma" size="2">
				</font>
		</p>
		<h1>
				<a name="SECTION0013200000000000000000">
				</a>
				<a name="templating">
				</a>
				<br />
				<font face="Tahoma" size="2">11.2 Templating </font>
		</h1>
		<p>
				<font face="Tahoma" size="2">The </font>
				<a class="ulink" href="http://www.python.org/doc/lib/module-string.html">
						<tt class="module">
								<font face="Tahoma">
										<font size="2">
												<font color="#002c99">string</font>
										</font>
								</font>
						</tt>
				</a>
				<font face="Tahoma" size="2">module includes a versatile <tt class="class">Template</tt> class with a simplified syntax suitable for editing by end-users. This allows users to customize their applications without having to alter the application. </font>
		</p>
		<p>
				<font face="Tahoma" size="2">The format uses placeholder names formed by "<tt class="samp">$</tt>" with valid Python identifiers (alphanumeric characters and underscores). Surrounding the placeholder with braces allows it to be followed by more alphanumeric letters with no intervening spaces. Writing "<tt class="samp">$$</tt>" creates a single escaped "<tt class="samp">$</tt>": </font>
		</p>
		<p>
				<font face="Tahoma" size="2">
				</font>
		</p>
		<div class="verbatim">
				<pre>
						<font face="Tahoma" size="2">												&gt;&gt;&gt; from string import Template
&gt;&gt;&gt; t = Template('${village}folk send $$10 to $cause.')
&gt;&gt;&gt; t.substitute(village='Nottingham', cause='the ditch fund')
'Nottinghamfolk send $10 to the ditch fund.'

				
				</font>
				</pre>
		</div>
		<p>
				<font face="Tahoma" size="2">The <tt class="method">substitute</tt> method raises a <tt class="exception">KeyError</tt> when a placeholder is not supplied in a dictionary or a keyword argument. For mail-merge style applications, user supplied data may be incomplete and the <tt class="method">safe_substitute</tt> method may be more appropriate -- it will leave placeholders unchanged if data is missing: </font>
		</p>
		<p>
				<font face="Tahoma" size="2">
				</font>
		</p>
		<div class="verbatim">
				<pre>
						<font face="Tahoma" size="2">												&gt;&gt;&gt; t = Template('Return the $item to $owner.')
&gt;&gt;&gt; d = dict(item='unladen swallow')
&gt;&gt;&gt; t.substitute(d)
Traceback (most recent call last):
  . . .
KeyError: 'owner'
&gt;&gt;&gt; t.safe_substitute(d)
'Return the unladen swallow to $owner.'

				
				</font>
				</pre>
		</div>
		<p>
				<font face="Tahoma" size="2">Template subclasses can specify a custom delimiter. For example, a batch renaming utility for a photo browser may elect to use percent signs for placeholders such as the current date, image sequence number, or file format: </font>
		</p>
		<p>
				<font face="Tahoma" size="2">
				</font>
		</p>
		<div class="verbatim">
				<pre>
						<font face="Tahoma" size="2">												&gt;&gt;&gt; import time, os.path
&gt;&gt;&gt; photofiles = ['img_1074.jpg', 'img_1076.jpg', 'img_1077.jpg']
&gt;&gt;&gt; class BatchRename(Template):
...     delimiter = '%'
&gt;&gt;&gt; fmt = raw_input('Enter rename style (%d-date %n-seqnum %f-format):  ')
Enter rename style (%d-date %n-seqnum %f-format):  Ashley_%n%f

&gt;&gt;&gt; t = BatchRename(fmt)
&gt;&gt;&gt; date = time.strftime('%d%b%y')
&gt;&gt;&gt; for i, filename in enumerate(photofiles):
...     base, ext = os.path.splitext(filename)
...     newname = t.substitute(d=date, n=i, f=ext)
...     print '%s --&gt; %s' % (filename, newname)

img_1074.jpg --&gt; Ashley_0.jpg
img_1076.jpg --&gt; Ashley_1.jpg
img_1077.jpg --&gt; Ashley_2.jpg

				
				</font>
				</pre>
		</div>
		<p>
				<font face="Tahoma" size="2">Another application for templating is separating program logic from the details of multiple output formats. This makes it possible to substitute custom templates for XML files, plain text reports, and HTML web reports. </font>
		</p>
		<p>
				<font face="Tahoma" size="2">
				</font>
		</p>
		<h1>
				<a name="SECTION0013300000000000000000">
				</a>
				<a name="binary-formats">
				</a>
				<br />
				<font face="Tahoma" size="2">11.3 Working with Binary Data Record Layouts </font>
		</h1>
		<p>
				<font face="Tahoma" size="2">The </font>
				<a class="ulink" href="http://www.python.org/doc/lib/module-struct.html">
						<tt class="module">
								<font face="Tahoma">
										<font size="2">
												<font color="#002c99">struct</font>
										</font>
								</font>
						</tt>
				</a>
				<font face="Tahoma" size="2">module provides <tt class="function">pack()</tt> and <tt class="function">unpack()</tt> functions for working with variable length binary record formats. The following example shows how to loop through header information in a ZIP file (with pack codes <code>"H"</code> and <code>"L"</code> representing two and four byte unsigned numbers respectively): </font>
		</p>
		<p>
				<font face="Tahoma" size="2">
				</font>
		</p>
		<div class="verbatim">
				<pre>
						<font face="Tahoma" size="2">												    import struct

    data = open('myfile.zip', 'rb').read()
    start = 0
    for i in range(3):                      # show the first 3 file headers
        start += 14
        fields = struct.unpack('LLLHH', data[start:start+16])
        crc32, comp_size, uncomp_size, filenamesize, extra_size = fields

        start += 16
        filename = data[start:start+filenamesize]
        start += filenamesize
        extra = data[start:start+extra_size]
        print filename, hex(crc32), comp_size, uncomp_size

        start += extra_size + comp_size     # skip to the next header

				
				</font>
				</pre>
		</div>
		<p>
				<font face="Tahoma" size="2">
				</font>
		</p>
		<h1>
				<a name="SECTION0013400000000000000000">
				</a>
				<a name="multi-threading">
				</a>
				<br />
				<font face="Tahoma" size="2">11.4 Multi-threading </font>
		</h1>
		<p>
				<font face="Tahoma" size="2">Threading is a technique for decoupling tasks which are not sequentially dependent. Threads can be used to improve the responsiveness of applications that accept user input while other tasks run in the background. A related use case is running I/O in parallel with computations in another thread. </font>
		</p>
		<p>
				<font face="Tahoma" size="2">The following code shows how the high level </font>
				<a class="ulink" href="http://www.python.org/doc/lib/module-threading.html">
						<tt class="module">
								<font face="Tahoma">
										<font size="2">
												<font color="#002c99">threading</font>
										</font>
								</font>
						</tt>
				</a>
				<font face="Tahoma" size="2">module can run tasks in background while the main program continues to run: </font>
		</p>
		<p>
				<font face="Tahoma" size="2">
				</font>
		</p>
		<div class="verbatim">
				<pre>
						<font face="Tahoma" size="2">												    import threading, zipfile

    class AsyncZip(threading.Thread):
        def __init__(self, infile, outfile):
            threading.Thread.__init__(self)        
            self.infile = infile
            self.outfile = outfile
        def run(self):
            f = zipfile.ZipFile(self.outfile, 'w', zipfile.ZIP_DEFLATED)
            f.write(self.infile)
            f.close()
            print 'Finished background zip of: ', self.infile

    background = AsyncZip('mydata.txt', 'myarchive.zip')
    background.start()
    print 'The main program continues to run in foreground.'
    
    background.join()    # Wait for the background task to finish
    print 'Main program waited until background was done.'

				
				</font>
				</pre>
		</div>
		<p>
				<font face="Tahoma" size="2">The principal challenge of multi-threaded applications is coordinating threads that share data or other resources. To that end, the threading module provides a number of synchronization primitives including locks, events, condition variables, and semaphores. </font>
		</p>
		<p>
				<font face="Tahoma" size="2">While those tools are powerful, minor design errors can result in problems that are difficult to reproduce. So, the preferred approach to task coordination is to concentrate all access to a resource in a single thread and then use the </font>
				<a class="ulink" href="http://www.python.org/doc/lib/module-Queue.html">
						<tt class="module">
								<font face="Tahoma">
										<font size="2">
												<font color="#002c99">Queue</font>
										</font>
								</font>
						</tt>
				</a>
				<font face="Tahoma" size="2">module to feed that thread with requests from other threads. Applications using <tt class="class">Queue</tt> objects for inter-thread communication and coordination are easier to design, more readable, and more reliable. </font>
		</p>
		<p>
				<font face="Tahoma" size="2">
				</font>
		</p>
		<h1>
				<a name="SECTION0013500000000000000000">
				</a>
				<a name="logging">
				</a>
				<br />
				<font face="Tahoma" size="2">11.5 Logging </font>
		</h1>
		<p>
				<font face="Tahoma" size="2">The </font>
				<a class="ulink" href="http://www.python.org/doc/lib/module-logging.html">
						<tt class="module">
								<font face="Tahoma">
										<font size="2">
												<font color="#002c99">logging</font>
										</font>
								</font>
						</tt>
				</a>
				<font face="Tahoma" size="2">module offers a full featured and flexible logging system. At its simplest, log messages are sent to a file or to <code>sys.stderr</code>: </font>
		</p>
		<p>
				<font face="Tahoma" size="2">
				</font>
		</p>
		<div class="verbatim">
				<pre>
						<font face="Tahoma" size="2">												    import logging
    logging.debug('Debugging information')
    logging.info('Informational message')
    logging.warning('Warning:config file %s not found', 'server.conf')
    logging.error('Error occurred')
    logging.critical('Critical error -- shutting down')

				
				</font>
				</pre>
		</div>
		<p>
				<font face="Tahoma" size="2">This produces the following output: </font>
		</p>
		<p>
				<font face="Tahoma" size="2">
				</font>
		</p>
		<div class="verbatim">
				<pre>
						<font face="Tahoma" size="2">												    WARNING:root:Warning:config file server.conf not found
    ERROR:root:Error occurred
    CRITICAL:root:Critical error -- shutting down

				
				</font>
				</pre>
		</div>
		<p>
				<font face="Tahoma" size="2">By default, informational and debugging messages are suppressed and the output is sent to standard error. Other output options include routing messages through email, datagrams, sockets, or to an HTTP Server. New filters can select different routing based on message priority: <tt class="constant">DEBUG</tt>, <tt class="constant">INFO</tt>, <tt class="constant">WARNING</tt>, <tt class="constant">ERROR</tt>, and <tt class="constant">CRITICAL</tt>. </font>
		</p>
		<p>
				<font face="Tahoma" size="2">The logging system can be configured directly from Python or can be loaded from a user editable configuration file for customized logging without altering the application. </font>
		</p>
		<p>
				<font face="Tahoma" size="2">
				</font>
		</p>
		<h1>
				<a name="SECTION0013600000000000000000">
				</a>
				<a name="weak-references">
				</a>
				<br />
				<font face="Tahoma" size="2">11.6 Weak References </font>
		</h1>
		<p>
				<font face="Tahoma" size="2">Python does automatic memory management (reference counting for most objects and garbage collection to eliminate cycles). The memory is freed shortly after the last reference to it has been eliminated. </font>
		</p>
		<p>
				<font face="Tahoma" size="2">This approach works fine for most applications but occasionally there is a need to track objects only as long as they are being used by something else. Unfortunately, just tracking them creates a reference that makes them permanent. The </font>
				<a class="ulink" href="http://www.python.org/doc/lib/module-weakref.html">
						<tt class="module">
								<font face="Tahoma">
										<font size="2">
												<font color="#002c99">weakref</font>
										</font>
								</font>
						</tt>
				</a>
				<font face="Tahoma" size="2">module provides tools for tracking objects without creating a reference. When the object is no longer needed, it is automatically removed from a weakref table and a callback is triggered for weakref objects. Typical applications include caching objects that are expensive to create: </font>
		</p>
		<p>
				<font face="Tahoma" size="2">
				</font>
		</p>
		<div class="verbatim">
				<pre>
						<font face="Tahoma" size="2">												    &gt;&gt;&gt; import weakref, gc
    &gt;&gt;&gt; class A:
    ...     def __init__(self, value):
    ...             self.value = value
    ...     def __repr__(self):
    ...             return str(self.value)
    ...
    &gt;&gt;&gt; a = A(10)                   # create a reference
    &gt;&gt;&gt; d = weakref.WeakValueDictionary()
    &gt;&gt;&gt; d['primary'] = a            # does not create a reference
    &gt;&gt;&gt; d['primary']                # fetch the object if it is still alive
    10
    &gt;&gt;&gt; del a                       # remove the one reference
    &gt;&gt;&gt; gc.collect()                # run garbage collection right away
    0
    &gt;&gt;&gt; d['primary']                # entry was automatically removed
    Traceback (most recent call last):
      File "&lt;pyshell#108&gt;", line 1, in -toplevel-
        d['primary']                # entry was automatically removed
      File "C:/PY24/lib/weakref.py", line 46, in __getitem__
        o = self.data[key]()
    KeyError: 'primary'

				
				</font>
				</pre>
		</div>
		<p>
				<font face="Tahoma" size="2">
				</font>
		</p>
		<h1>
				<a name="SECTION0013700000000000000000">
				</a>
				<a name="list-tools">
				</a>
				<br />
				<font face="Tahoma" size="2">11.7 Tools for Working with Lists </font>
		</h1>
		<p>
				<font face="Tahoma" size="2">Many data structure needs can be met with the built-in list type. However, sometimes there is a need for alternative implementations with different performance trade-offs. </font>
		</p>
		<p>
				<font face="Tahoma" size="2">The </font>
				<a class="ulink" href="http://www.python.org/doc/lib/module-array.html">
						<tt class="module">
								<font face="Tahoma">
										<font size="2">
												<font color="#002c99">array</font>
										</font>
								</font>
						</tt>
				</a>
				<font face="Tahoma" size="2">module provides an <tt class="class">array()</tt> object that is like a list that stores only homogenous data but stores it more compactly. The following example shows an array of numbers stored as two byte unsigned binary numbers (typecode <code>"H"</code>) rather than the usual 16 bytes per entry for regular lists of python int objects: </font>
		</p>
		<p>
				<font face="Tahoma" size="2">
				</font>
		</p>
		<div class="verbatim">
				<pre>
						<font face="Tahoma" size="2">												    &gt;&gt;&gt; from array import array
    &gt;&gt;&gt; a = array('H', [4000, 10, 700, 22222])
    &gt;&gt;&gt; sum(a)
    26932
    &gt;&gt;&gt; a[1:3]
    array('H', [10, 700])

				
				</font>
				</pre>
		</div>
		<p>
				<font face="Tahoma" size="2">The </font>
				<a class="ulink" href="http://www.python.org/doc/lib/module-collections.html">
						<tt class="module">
								<font face="Tahoma">
										<font size="2">
												<font color="#002c99">collections</font>
										</font>
								</font>
						</tt>
				</a>
				<font face="Tahoma" size="2">module provides a <tt class="class">deque()</tt> object that is like a list with faster appends and pops from the left side but slower lookups in the middle. These objects are well suited for implementing queues and breadth first tree searches: </font>
		</p>
		<p>
				<font face="Tahoma" size="2">
				</font>
		</p>
		<div class="verbatim">
				<pre>
						<font face="Tahoma" size="2">												    &gt;&gt;&gt; from collections import deque
    &gt;&gt;&gt; d = deque(["task1", "task2", "task3"])
    &gt;&gt;&gt; d.append("task4")
    &gt;&gt;&gt; print "Handling", d.popleft()
    Handling task1

    unsearched = deque([starting_node])
    def breadth_first_search(unsearched):
        node = unsearched.popleft()
        for m in gen_moves(node):
            if is_goal(m):
                return m
            unsearched.append(m)

				
				</font>
				</pre>
		</div>
		<p>
				<font face="Tahoma" size="2">In addition to alternative list implementations, the library also offers other tools such as the </font>
				<a class="ulink" href="http://www.python.org/doc/lib/module-bisect.html">
						<tt class="module">
								<font face="Tahoma">
										<font size="2">
												<font color="#002c99">bisect</font>
										</font>
								</font>
						</tt>
				</a>
				<font face="Tahoma" size="2">module with functions for manipulating sorted lists: </font>
		</p>
		<p>
				<font face="Tahoma" size="2">
				</font>
		</p>
		<div class="verbatim">
				<pre>
						<font face="Tahoma" size="2">												    &gt;&gt;&gt; import bisect
    &gt;&gt;&gt; scores = [(100, 'perl'), (200, 'tcl'), (400, 'lua'), (500, 'python')]
    &gt;&gt;&gt; bisect.insort(scores, (300, 'ruby'))
    &gt;&gt;&gt; scores
    [(100, 'perl'), (200, 'tcl'), (300, 'ruby'), (400, 'lua'), (500, 'python')]

				
				</font>
				</pre>
		</div>
		<p>
				<font face="Tahoma" size="2">The </font>
				<a class="ulink" href="http://www.python.org/doc/lib/module-heapq.html">
						<tt class="module">
								<font face="Tahoma">
										<font size="2">
												<font color="#002c99">heapq</font>
										</font>
								</font>
						</tt>
				</a>
				<font face="Tahoma" size="2">module provides functions for implementing heaps based on regular lists. The lowest valued entry is always kept at position zero. This is useful for applications which repeatedly access the smallest element but do not want to run a full list sort: </font>
		</p>
		<p>
				<font face="Tahoma" size="2">
				</font>
		</p>
		<div class="verbatim">
				<pre>
						<font face="Tahoma" size="2">												    &gt;&gt;&gt; from heapq import heapify, heappop, heappush
    &gt;&gt;&gt; data = [1, 3, 5, 7, 9, 2, 4, 6, 8, 0]
    &gt;&gt;&gt; heapify(data)                      # rearrange the list into heap order
    &gt;&gt;&gt; heappush(data, -5)                 # add a new entry
    &gt;&gt;&gt; [heappop(data) for i in range(3)]  # fetch the three smallest entries
    [-5, 0, 1]

				
				</font>
				</pre>
		</div>
		<p>
				<font face="Tahoma" size="2">
				</font>
		</p>
		<h1>
				<a name="SECTION0013800000000000000000">
				</a>
				<a name="decimal-fp">
				</a>
				<br />
				<font face="Tahoma" size="2">11.8 Decimal Floating Point Arithmetic </font>
		</h1>
		<p>
				<font face="Tahoma" size="2">The </font>
				<a class="ulink" href="http://www.python.org/doc/lib/module-decimal.html">
						<tt class="module">
								<font face="Tahoma">
										<font size="2">
												<font color="#002c99">decimal</font>
										</font>
								</font>
						</tt>
				</a>
				<font face="Tahoma" size="2">module offers a <tt class="class">Decimal</tt> datatype for decimal floating point arithmetic. Compared to the built-in <tt class="class">float</tt> implementation of binary floating point, the new class is especially helpful for financial applications and other uses which require exact decimal representation, control over precision, control over rounding to meet legal or regulatory requirements, tracking of significant decimal places, or for applications where the user expects the results to match calculations done by hand. </font>
		</p>
		<p>
				<font face="Tahoma" size="2">For example, calculating a 5% tax on a 70 cent phone charge gives different results in decimal floating point and binary floating point. The difference becomes significant if the results are rounded to the nearest cent: </font>
		</p>
		<p>
				<font face="Tahoma" size="2">
				</font>
		</p>
		<div class="verbatim">
				<pre>
						<font face="Tahoma" size="2">												&gt;&gt;&gt; from decimal import *       
&gt;&gt;&gt; Decimal('0.70') * Decimal('1.05')
Decimal("0.7350")
&gt;&gt;&gt; .70 * 1.05
0.73499999999999999

				
				</font>
				</pre>
		</div>
		<p>
				<font face="Tahoma" size="2">The <tt class="class">Decimal</tt> result keeps a trailing zero, automatically inferring four place significance from multiplicands with two place significance. Decimal reproduces mathematics as done by hand and avoids issues that can arise when binary floating point cannot exactly represent decimal quantities. </font>
		</p>
		<p>
				<font face="Tahoma" size="2">Exact representation enables the <tt class="class">Decimal</tt> class to perform modulo calculations and equality tests that are unsuitable for binary floating point: </font>
		</p>
		<p>
				<font face="Tahoma" size="2">
				</font>
		</p>
		<div class="verbatim">
				<pre>
						<font face="Tahoma" size="2">												&gt;&gt;&gt; Decimal('1.00') % Decimal('.10')
Decimal("0.00")
&gt;&gt;&gt; 1.00 % 0.10
0.09999999999999995
       
&gt;&gt;&gt; sum([Decimal('0.1')]*10) == Decimal('1.0')
True
&gt;&gt;&gt; sum([0.1]*10) == 1.0
False

				
				</font>
				</pre>
		</div>
		<p>
				<font face="Tahoma" size="2">The <tt class="module">decimal</tt> module provides arithmetic with as much precision as needed: </font>
		</p>
		<p>
				<font face="Tahoma" size="2">
				</font>
		</p>
		<div class="verbatim">
				<pre>
						<font face="Tahoma" size="2">												&gt;&gt;&gt; getcontext().prec = 36
&gt;&gt;&gt; Decimal(1) / Decimal(7)
Decimal("0.142857142857142857142857142857142857")

				
				</font>
				</pre>
		</div>
<img src ="http://www.cppblog.com/Jeff-Chen/aggbug/5484.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.cppblog.com/Jeff-Chen/" target="_blank">Jeff-Chen</a> 2006-04-13 19:45 <a href="http://www.cppblog.com/Jeff-Chen/archive/2006/04/13/5484.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item><item><title>Python 学习之路（Brief Outlook of Library:One）</title><link>http://www.cppblog.com/Jeff-Chen/archive/2006/04/13/5483.html</link><dc:creator>Jeff-Chen</dc:creator><author>Jeff-Chen</author><pubDate>Thu, 13 Apr 2006 11:43:00 GMT</pubDate><guid>http://www.cppblog.com/Jeff-Chen/archive/2006/04/13/5483.html</guid><wfw:comment>http://www.cppblog.com/Jeff-Chen/comments/5483.html</wfw:comment><comments>http://www.cppblog.com/Jeff-Chen/archive/2006/04/13/5483.html#Feedback</comments><slash:comments>0</slash:comments><wfw:commentRss>http://www.cppblog.com/Jeff-Chen/comments/commentRss/5483.html</wfw:commentRss><trackback:ping>http://www.cppblog.com/Jeff-Chen/services/trackbacks/5483.html</trackback:ping><description><![CDATA[
		<a name="CHILD_LINKS">
				<strong>Subsections</strong>
		</a>
		<ul class="ChildLinks">
				<li>
						<a href="http://www.python.org/doc/tut/node12.html#SECTION0012100000000000000000">10.1 Operating System Interface</a>
				</li>
				<li>
						<a href="http://www.python.org/doc/tut/node12.html#SECTION0012200000000000000000">10.2 File Wildcards</a>
				</li>
				<li>
						<a href="http://www.python.org/doc/tut/node12.html#SECTION0012300000000000000000">10.3 Command Line Arguments</a>
				</li>
				<li>
						<a href="http://www.python.org/doc/tut/node12.html#SECTION0012400000000000000000">10.4 Error Output Redirection and Program Termination</a>
				</li>
				<li>
						<a href="http://www.python.org/doc/tut/node12.html#SECTION0012500000000000000000">10.5 String Pattern Matching</a>
				</li>
				<li>
						<a href="http://www.python.org/doc/tut/node12.html#SECTION0012600000000000000000">10.6 Mathematics</a>
				</li>
				<li>
						<a href="http://www.python.org/doc/tut/node12.html#SECTION0012700000000000000000">10.7 Internet Access</a>
				</li>
				<li>
						<a href="http://www.python.org/doc/tut/node12.html#SECTION0012800000000000000000">10.8 Dates and Times</a>
				</li>
				<li>
						<a href="http://www.python.org/doc/tut/node12.html#SECTION0012900000000000000000">10.9 Data Compression</a>
				</li>
				<li>
						<a href="http://www.python.org/doc/tut/node12.html#SECTION00121000000000000000000">10.10 Performance Measurement</a>
				</li>
				<li>
						<a href="http://www.python.org/doc/tut/node12.html#SECTION00121100000000000000000">10.11 Quality Control</a>
				</li>
				<li>
						<a href="http://www.python.org/doc/tut/node12.html#SECTION00121200000000000000000">10.12 Batteries Included</a>
				</li>
		</ul>
		<!--End of Table of Child-Links-->
		<hr />
		<h1>
				<a name="SECTION0012000000000000000000">
				</a>
				<a name="briefTour">
				</a>
				<br />10. Brief Tour of the Standard Library </h1>
		<p>
		</p>
		<h1>
				<a name="SECTION0012100000000000000000">
				</a>
				<a name="os-interface">
				</a>
				<br />10.1 Operating System Interface </h1>
		<p>The <a class="ulink" href="http://www.python.org/doc/lib/module-os.html"><tt class="module">os</tt></a> module provides dozens of functions for interacting with the operating system: 
</p>
		<p>
		</p>
		<div class="verbatim">
				<pre>&gt;&gt;&gt; import os
&gt;&gt;&gt; os.system('time 0:02')
0
&gt;&gt;&gt; os.getcwd()      # Return the current working directory
'C:\\Python24'
&gt;&gt;&gt; os.chdir('/server/accesslogs')
</pre>
		</div>
		<p>Be sure to use the "<tt class="samp">import os</tt>" style instead of "<tt class="samp">from os import *</tt>". This will keep <tt class="function">os.open()</tt> from shadowing the builtin <tt class="function">open()</tt> function which operates much differently. 
</p>
		<p>
				<a id="l2h-34" xml:id="l2h-34">
				</a>The builtin <tt class="function">dir()</tt> and <tt class="function">help()</tt> functions are useful as interactive aids for working with large modules like <tt class="module">os</tt>: 
</p>
		<p>
		</p>
		<div class="verbatim">
				<pre>&gt;&gt;&gt; import os
&gt;&gt;&gt; dir(os)
&lt;returns a list of all module functions&gt;
&gt;&gt;&gt; help(os)
&lt;returns an extensive manual page created from the module's docstrings&gt;
</pre>
		</div>
		<p>For daily file and directory management tasks, the <a class="ulink" href="http://www.python.org/doc/lib/module-shutil.html"><tt class="module">shutil</tt></a> module provides a higher level interface that is easier to use: 
</p>
		<p>
		</p>
		<div class="verbatim">
				<pre>&gt;&gt;&gt; import shutil
&gt;&gt;&gt; shutil.copyfile('data.db', 'archive.db')
&gt;&gt;&gt; shutil.move('/build/executables', 'installdir')
</pre>
		</div>
		<p>
		</p>
		<h1>
				<a name="SECTION0012200000000000000000">
				</a>
				<a name="file-wildcards">
				</a>
				<br />10.2 File Wildcards </h1>
		<p>The <a class="ulink" href="http://www.python.org/doc/lib/module-glob.html"><tt class="module">glob</tt></a> module provides a function for making file lists from directory wildcard searches: 
</p>
		<p>
		</p>
		<div class="verbatim">
				<pre>&gt;&gt;&gt; import glob
&gt;&gt;&gt; glob.glob('*.py')
['primes.py', 'random.py', 'quote.py']
</pre>
		</div>
		<p>
		</p>
		<h1>
				<a name="SECTION0012300000000000000000">
				</a>
				<a name="command-line-arguments">
				</a>
				<br />10.3 Command Line Arguments </h1>
		<p>Common utility scripts often need to process command line arguments. These arguments are stored in the <a class="ulink" href="http://www.python.org/doc/lib/module-sys.html"><tt class="module">sys</tt></a> module's <var>argv</var> attribute as a list. For instance the following output results from running "<tt class="samp">python demo.py one two three</tt>" at the command line: 
</p>
		<p>
		</p>
		<div class="verbatim">
				<pre>&gt;&gt;&gt; import sys
&gt;&gt;&gt; print sys.argv
['demo.py', 'one', 'two', 'three']
</pre>
		</div>
		<p>The <a class="ulink" href="http://www.python.org/doc/lib/module-getopt.html"><tt class="module">getopt</tt></a> module processes <var>sys.argv</var> using the conventions of the <span class="Unix">Unix</span><tt class="function">getopt()</tt> function. More powerful and flexible command line processing is provided by the <a class="ulink" href="http://www.python.org/doc/lib/module-optparse.html"><tt class="module">optparse</tt></a> module. 
</p>
		<p>
		</p>
		<h1>
				<a name="SECTION0012400000000000000000">
				</a>
				<a name="stderr">
				</a>
				<br />10.4 Error Output Redirection and Program Termination </h1>
		<p>The <a class="ulink" href="http://www.python.org/doc/lib/module-sys.html"><tt class="module">sys</tt></a> module also has attributes for <var>stdin</var>, <var>stdout</var>, and <var>stderr</var>. The latter is useful for emitting warnings and error messages to make them visible even when <var>stdout</var> has been redirected: 
</p>
		<p>
		</p>
		<div class="verbatim">
				<pre>&gt;&gt;&gt; sys.stderr.write('Warning, log file not found starting a new one\n')
Warning, log file not found starting a new one
</pre>
		</div>
		<p>The most direct way to terminate a script is to use "<tt class="samp">sys.exit()</tt>". 
</p>
		<p>
		</p>
		<h1>
				<a name="SECTION0012500000000000000000">
				</a>
				<a name="string-pattern-matching">
				</a>
				<br />10.5 String Pattern Matching </h1>
		<p>The <a class="ulink" href="http://www.python.org/doc/lib/module-re.html"><tt class="module">re</tt></a> module provides regular expression tools for advanced string processing. For complex matching and manipulation, regular expressions offer succinct, optimized solutions: 
</p>
		<p>
		</p>
		<div class="verbatim">
				<pre>&gt;&gt;&gt; import re
&gt;&gt;&gt; re.findall(r'\bf[a-z]*', 'which foot or hand fell fastest')
['foot', 'fell', 'fastest']
&gt;&gt;&gt; re.sub(r'(\b[a-z]+) \1', r'\1', 'cat in the the hat')
'cat in the hat'
</pre>
		</div>
		<p>When only simple capabilities are needed, string methods are preferred because they are easier to read and debug: 
</p>
		<p>
		</p>
		<div class="verbatim">
				<pre>&gt;&gt;&gt; 'tea for too'.replace('too', 'two')
'tea for two'
</pre>
		</div>
		<p>
		</p>
		<h1>
				<a name="SECTION0012600000000000000000">
				</a>
				<a name="mathematics">
				</a>
				<br />10.6 Mathematics </h1>
		<p>The <a class="ulink" href="http://www.python.org/doc/lib/module-math.html"><tt class="module">math</tt></a> module gives access to the underlying C library functions for floating point math: 
</p>
		<p>
		</p>
		<div class="verbatim">
				<pre>&gt;&gt;&gt; import math
&gt;&gt;&gt; math.cos(math.pi / 4.0)
0.70710678118654757
&gt;&gt;&gt; math.log(1024, 2)
10.0
</pre>
		</div>
		<p>The <a class="ulink" href="http://www.python.org/doc/lib/module-random.html"><tt class="module">random</tt></a> module provides tools for making random selections: 
</p>
		<p>
		</p>
		<div class="verbatim">
				<pre>&gt;&gt;&gt; import random
&gt;&gt;&gt; random.choice(['apple', 'pear', 'banana'])
'apple'
&gt;&gt;&gt; random.sample(xrange(100), 10)   # sampling without replacement
[30, 83, 16, 4, 8, 81, 41, 50, 18, 33]
&gt;&gt;&gt; random.random()    # random float
0.17970987693706186
&gt;&gt;&gt; random.randrange(6)    # random integer chosen from range(6)
4
</pre>
		</div>
		<p>
		</p>
		<h1>
				<a name="SECTION0012700000000000000000">
				</a>
				<a name="internet-access">
				</a>
				<br />10.7 Internet Access </h1>
		<p>There are a number of modules for accessing the internet and processing internet protocols. Two of the simplest are <a class="ulink" href="http://www.python.org/doc/lib/module-urllib2.html"><tt class="module">urllib2</tt></a> for retrieving data from urls and <a class="ulink" href="http://www.python.org/doc/lib/module-smtplib.html"><tt class="module">smtplib</tt></a> for sending mail: 
</p>
		<p>
		</p>
		<div class="verbatim">
				<pre>&gt;&gt;&gt; import urllib2
&gt;&gt;&gt; for line in urllib2.urlopen('http://tycho.usno.navy.mil/cgi-bin/timer.pl'):
...     if 'EST' in line:      # look for Eastern Standard Time
...         print line
    
&lt;BR&gt;Nov. 25, 09:43:32 PM EST

&gt;&gt;&gt; import smtplib
&gt;&gt;&gt; server = smtplib.SMTP('localhost')
&gt;&gt;&gt; server.sendmail('soothsayer@example.org', 'jcaesar@example.org',
"""To: jcaesar@example.org
From: soothsayer@example.org

Beware the Ides of March.
""")
&gt;&gt;&gt; server.quit()
</pre>
		</div>
		<p>
		</p>
		<h1>
				<a name="SECTION0012800000000000000000">
				</a>
				<a name="dates-and-times">
				</a>
				<br />10.8 Dates and Times </h1>
		<p>The <a class="ulink" href="http://www.python.org/doc/lib/module-datetime.html"><tt class="module">datetime</tt></a> module supplies classes for manipulating dates and times in both simple and complex ways. While date and time arithmetic is supported, the focus of the implementation is on efficient member extraction for output formatting and manipulation. The module also supports objects that are time zone aware. 
</p>
		<p>
		</p>
		<div class="verbatim">
				<pre># dates are easily constructed and formatted
&gt;&gt;&gt; from datetime import date
&gt;&gt;&gt; now = date.today()
&gt;&gt;&gt; now
datetime.date(2003, 12, 2)
&gt;&gt;&gt; now.strftime("%m-%d-%y. %d %b %Y is a %A on the %d day of %B.")
'12-02-03. 02 Dec 2003 is a Tuesday on the 02 day of December.'

# dates support calendar arithmetic
&gt;&gt;&gt; birthday = date(1964, 7, 31)
&gt;&gt;&gt; age = now - birthday
&gt;&gt;&gt; age.days
14368
</pre>
		</div>
		<p>
		</p>
		<h1>
				<a name="SECTION0012900000000000000000">
				</a>
				<a name="data-compression">
				</a>
				<br />10.9 Data Compression </h1>
		<p>Common data archiving and compression formats are directly supported by modules including: <a class="ulink" href="http://www.python.org/doc/lib/module-zlib.html"><tt class="module">zlib</tt></a>, <a class="ulink" href="http://www.python.org/doc/lib/module-gzip.html"><tt class="module">gzip</tt></a>, <a class="ulink" href="http://www.python.org/doc/lib/module-bz2.html"><tt class="module">bz2</tt></a>, <a class="ulink" href="http://www.python.org/doc/lib/module-zipfile.html"><tt class="module">zipfile</tt></a>, and <a class="ulink" href="http://www.python.org/doc/lib/module-tarfile.html"><tt class="module">tarfile</tt></a>. 
</p>
		<p>
		</p>
		<div class="verbatim">
				<pre>&gt;&gt;&gt; import zlib
&gt;&gt;&gt; s = 'witch which has which witches wrist watch'
&gt;&gt;&gt; len(s)
41
&gt;&gt;&gt; t = zlib.compress(s)
&gt;&gt;&gt; len(t)
37
&gt;&gt;&gt; zlib.decompress(t)
'witch which has which witches wrist watch'
&gt;&gt;&gt; zlib.crc32(s)
226805979
</pre>
		</div>
		<p>
		</p>
		<h1>
				<a name="SECTION00121000000000000000000">
				</a>
				<a name="performance-measurement">
				</a>
				<br />10.10 Performance Measurement </h1>
		<p>Some Python users develop a deep interest in knowing the relative performance of different approaches to the same problem. Python provides a measurement tool that answers those questions immediately. 
</p>
		<p>For example, it may be tempting to use the tuple packing and unpacking feature instead of the traditional approach to swapping arguments. The <a class="ulink" href="http://www.python.org/doc/lib/module-timeit.html"><tt class="module">timeit</tt></a> module quickly demonstrates a modest performance advantage: 
</p>
		<p>
		</p>
		<div class="verbatim">
				<pre>&gt;&gt;&gt; from timeit import Timer
&gt;&gt;&gt; Timer('t=a; a=b; b=t', 'a=1; b=2').timeit()
0.57535828626024577
&gt;&gt;&gt; Timer('a,b = b,a', 'a=1; b=2').timeit()
0.54962537085770791
</pre>
		</div>
		<p>In contrast to <tt class="module">timeit</tt>'s fine level of granularity, the <a class="ulink" href="http://www.python.org/doc/lib/module-profile.html"><tt class="module">profile</tt></a> and <tt class="module">pstats</tt> modules provide tools for identifying time critical sections in larger blocks of code. 
</p>
		<p>
		</p>
		<h1>
				<a name="SECTION00121100000000000000000">
				</a>
				<a name="quality-control">
				</a>
				<br />10.11 Quality Control </h1>
		<p>One approach for developing high quality software is to write tests for each function as it is developed and to run those tests frequently during the development process. 
</p>
		<p>The <a class="ulink" href="http://www.python.org/doc/lib/module-doctest.html"><tt class="module">doctest</tt></a> module provides a tool for scanning a module and validating tests embedded in a program's docstrings. Test construction is as simple as cutting-and-pasting a typical call along with its results into the docstring. This improves the documentation by providing the user with an example and it allows the doctest module to make sure the code remains true to the documentation: 
</p>
		<p>
		</p>
		<div class="verbatim">
				<pre>def average(values):
    """Computes the arithmetic mean of a list of numbers.

    &gt;&gt;&gt; print average([20, 30, 70])
    40.0
    """
    return sum(values, 0.0) / len(values)

import doctest
doctest.testmod()   # automatically validate the embedded tests
</pre>
		</div>
		<p>The <a class="ulink" href="http://www.python.org/doc/lib/module-unittest.html"><tt class="module">unittest</tt></a> module is not as effortless as the <tt class="module">doctest</tt> module, but it allows a more comprehensive set of tests to be maintained in a separate file: 
</p>
		<p>
		</p>
		<div class="verbatim">
				<pre>import unittest

class TestStatisticalFunctions(unittest.TestCase):

    def test_average(self):
        self.assertEqual(average([20, 30, 70]), 40.0)
        self.assertEqual(round(average([1, 5, 7]), 1), 4.3)
        self.assertRaises(ZeroDivisionError, average, [])
        self.assertRaises(TypeError, average, 20, 30, 70)

unittest.main() # Calling from the command line invokes all tests
</pre>
		</div>
		<p>
		</p>
		<h1>
				<a name="SECTION00121200000000000000000">
				</a>
				<a name="batteries-included">
				</a>
				<br />10.12 Batteries Included </h1>
		<p>Python has a ``batteries included'' philosophy. This is best seen through the sophisticated and robust capabilities of its larger packages. For example: 
</p>
		<p>
		</p>
		<ul>
				<li>The <a class="ulink" href="http://www.python.org/doc/lib/module-xmlrpclib.html"><tt class="module">xmlrpclib</tt></a> and <a class="ulink" href="http://www.python.org/doc/lib/module-SimpleXMLRPCServer.html"><tt class="module">SimpleXMLRPCServer</tt></a> modules make implementing remote procedure calls into an almost trivial task. Despite the names, no direct knowledge or handling of XML is needed. 
</li>
				<li>The <a class="ulink" href="http://www.python.org/doc/lib/module-email.html"><tt class="module">email</tt></a> package is a library for managing email messages, including MIME and other RFC 2822-based message documents. Unlike <tt class="module">smtplib</tt> and <tt class="module">poplib</tt> which actually send and receive messages, the email package has a complete toolset for building or decoding complex message structures (including attachments) and for implementing internet encoding and header protocols. 
</li>
				<li>The <a class="ulink" href="http://www.python.org/doc/lib/module-xml.dom.html"><tt class="module">xml.dom</tt></a> and <a class="ulink" href="http://www.python.org/doc/lib/module-xml.sax.html"><tt class="module">xml.sax</tt></a> packages provide robust support for parsing this popular data interchange format. Likewise, the <a class="ulink" href="http://www.python.org/doc/lib/module-csv.html"><tt class="module">csv</tt></a> module supports direct reads and writes in a common database format. Together, these modules and packages greatly simplify data interchange between python applications and other tools. 
</li>
				<li>Internationalization is supported by a number of modules including <a class="ulink" href="http://www.python.org/doc/lib/module-gettext.html"><tt class="module">gettext</tt></a>, <a class="ulink" href="http://www.python.org/doc/lib/module-locale.html"><tt class="module">locale</tt></a>, and the <a class="ulink" href="http://www.python.org/doc/lib/module-codecs.html"><tt class="module">codecs</tt></a> package. </li>
		</ul>
<img src ="http://www.cppblog.com/Jeff-Chen/aggbug/5483.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.cppblog.com/Jeff-Chen/" target="_blank">Jeff-Chen</a> 2006-04-13 19:43 <a href="http://www.cppblog.com/Jeff-Chen/archive/2006/04/13/5483.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item><item><title>Python学习之路（三）</title><link>http://www.cppblog.com/Jeff-Chen/archive/2006/04/13/5444.html</link><dc:creator>Jeff-Chen</dc:creator><author>Jeff-Chen</author><pubDate>Thu, 13 Apr 2006 03:26:00 GMT</pubDate><guid>http://www.cppblog.com/Jeff-Chen/archive/2006/04/13/5444.html</guid><wfw:comment>http://www.cppblog.com/Jeff-Chen/comments/5444.html</wfw:comment><comments>http://www.cppblog.com/Jeff-Chen/archive/2006/04/13/5444.html#Feedback</comments><slash:comments>0</slash:comments><wfw:commentRss>http://www.cppblog.com/Jeff-Chen/comments/commentRss/5444.html</wfw:commentRss><trackback:ping>http://www.cppblog.com/Jeff-Chen/services/trackbacks/5444.html</trackback:ping><description><![CDATA[
		<p>
				<font style="BACKGROUND-COLOR: #f2f2f2">
						<font face="Arial">
								<font size="2">
										<strong>Python Reading Notes : (2006-4-13)<br />Note One : the powerful Lists</strong>
										<br />
								</font>
						</font>
						<font color="#0000ff">
								<font size="2">
										<font face="Arial">
												<em>Using Lists as Stacks<br /><font color="#000000"> </font><br /></em>
										</font>
										<font face="Tahoma" color="#000000">To add an item to the top of the stack, use <em>append()</em> ,To retrieve an item from the top of the stack, use <em>pop()</em> without an explicit index. For example: <br /></font>
								</font>
								<font face="Tahoma" color="#000000" size="2">&gt;&gt;&gt; stack = [3, 4, 5]<br />&gt;&gt;&gt; stack.append(6)<br />&gt;&gt;&gt; stack.append(7)<br />&gt;&gt;&gt; stack<br />[3, 4, 5, 6, 7]<br />&gt;&gt;&gt; stack.pop()<br />7<br />&gt;&gt;&gt; stack<br />[3, 4, 5, 6]<br />&gt;&gt;&gt; stack.pop()<br />6<br />&gt;&gt;&gt; stack.pop()<br />5<br />&gt;&gt;&gt; stack<br />[3, 4]<br /><br /></font>
								<em>
										<font face="Arial" size="2">Using Lists as Queues</font>
								</em>
						</font>
						<font face="Arial">
								<font size="2">
										<br />
										<br />
										<font face="Tahoma">To add an item to the back of the queue, use <em>append() </em>To retrieve an item from the front of the queue, use <em>pop()</em> with <em>0 </em>as the index. For example: <br /></font>
								</font>
								<font face="Tahoma" size="2">&gt;&gt;&gt; queue = ["Eric", "John", "Michael"]<br />&gt;&gt;&gt; queue.append("Terry")           # Terry arrives<br />&gt;&gt;&gt; queue.append("Graham")          # Graham arrives<br />&gt;&gt;&gt; queue.pop(0)<br />'Eric'<br />&gt;&gt;&gt; queue.pop(0)<br />'John'<br />&gt;&gt;&gt; queue<br />['Michael', 'Terry', 'Graham']<br /></font>
						</font>
				</font>
		</p>
		<p>
				<font size="2">
						<font style="BACKGROUND-COLOR: #f2f2f2">
								<font face="Arial">
										<strong>Note Two :about Tuples (distinguish between string type and  tuples tpye,especially zero or only one items contained in a tuples )<br /><br /></strong>
										<font face="Tahoma">A special problem is the construction of tuples containing 0 or 1 items: the syntax has some extra quirks to accommodate these. Empty tuples are constructed by an empty pair of parentheses; a tuple with one item is constructed by following a value with a comma (it is not sufficient to enclose a single value in parentheses). Ugly, but effective. For example: <br /></font>
										<font face="Tahoma">&gt;&gt;&gt; empty = ()<br />&gt;&gt;&gt; singleton = 'hello',    # &lt;-- note trailing comma<br />&gt;&gt;&gt; len(empty)<br />0<br />&gt;&gt;&gt; len(singleton)<br />1<br />&gt;&gt;&gt; singleton<br />('hello',)<br /><br /><br />but if you write a statement like this : <br />&gt;&gt;&gt; singleton = 'hello'          # it means that you define or construct a string type,not a tuples<br />&gt;&gt;&gt; singleton<br />'hello'<br />  </font>
										<br />
										<br />
								</font>
						</font>
				</font>
		</p>
<img src ="http://www.cppblog.com/Jeff-Chen/aggbug/5444.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.cppblog.com/Jeff-Chen/" target="_blank">Jeff-Chen</a> 2006-04-13 11:26 <a href="http://www.cppblog.com/Jeff-Chen/archive/2006/04/13/5444.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item><item><title>Python学习之路（二）</title><link>http://www.cppblog.com/Jeff-Chen/archive/2006/04/13/5441.html</link><dc:creator>Jeff-Chen</dc:creator><author>Jeff-Chen</author><pubDate>Thu, 13 Apr 2006 02:50:00 GMT</pubDate><guid>http://www.cppblog.com/Jeff-Chen/archive/2006/04/13/5441.html</guid><wfw:comment>http://www.cppblog.com/Jeff-Chen/comments/5441.html</wfw:comment><comments>http://www.cppblog.com/Jeff-Chen/archive/2006/04/13/5441.html#Feedback</comments><slash:comments>0</slash:comments><wfw:commentRss>http://www.cppblog.com/Jeff-Chen/comments/commentRss/5441.html</wfw:commentRss><trackback:ping>http://www.cppblog.com/Jeff-Chen/services/trackbacks/5441.html</trackback:ping><description><![CDATA[
		<strong>
				<font face="Arial" size="2">Python Reading Notes (2006-4-13)</font>
		</strong> <br /><br /><font face="Arial"><font size="2"><strong>Note One：about list (wow! so powerful)</strong><br /><br />Assignment to slices is also possible, and this can even change the size of the list,but you can not do that in the string type: <br />&gt;&gt;&gt; # Replace some items:<br />... a[0:2] = [1, 12]<br />&gt;&gt;&gt; a<br />[1, 12, 123, 1234]<br />&gt;&gt;&gt; # Remove some:<br />... a[0:2] = []<br />&gt;&gt;&gt; a<br />[123, 1234]<br />&gt;&gt;&gt; # Insert some:<br />... a[1:1] = ['bletch', 'xyzzy']<br />&gt;&gt;&gt; a<br />[123, 'bletch', 'xyzzy', 1234]<br />&gt;&gt;&gt; a[:0] = a     # Insert (a copy of) itself at the beginning<br />&gt;&gt;&gt; a<br />[123, 'bletch', 'xyzzy', 1234, 123, 'bletch', 'xyzzy', 1234]<br /><br /></font><p><font face="Tahoma" size="2">It is possible to nest lists (create lists containing other lists), for example: <br /></font><font size="2"><font face="Tahoma">&gt;&gt;&gt; q = [2, 3]<br />&gt;&gt;&gt; p = [1, q, 4]<br />&gt;&gt;&gt; len(p)<br />3<br />&gt;&gt;&gt; p[1]<br />[2, 3]<br />&gt;&gt;&gt; p[1][0]<br />2<br />&gt;&gt;&gt; p[1].append('xtra')    <br />&gt;&gt;&gt; p<br />[1, [2, 3, 'xtra'], 4]<br />&gt;&gt;&gt; q<br />[2, 3, 'xtra']</font><br /><br /><strong>Note Two : about for statement</strong></font></p><p><font size="2">It is not safe to modify the sequence being iterated over in the loop (this can only happen for mutable sequence types, such as lists). If you need to modify the list you are iterating over (for example, to duplicate selected items) you must iterate over a copy. The slice notation makes this particularly convenient: <br /><br /><em>valid statements: it will work normally<br /></em>&gt;&gt;&gt; for x in a[:]: # make a slice copy of the entire list<br />...       if len(x) &gt; 6: <br />...           a.insert(0, x)<br />... <br />&gt;&gt;&gt; a<br />['defenestrate', 'cat', 'window', 'defenestrate']<br /></font></p><p><font size="2"><em>invalid statement: you prompt will die</em><br /></font><font size="2">&gt;&gt;&gt; for x in a :  # make a slice copy of the entire list<br />...       if len(x) &gt; 6:<br />...          a.insert(0, x)<br />... </font></p><p><font size="2"><u>Note that:</u> in the first statement the first row ,the for statement ues 'a[:] ' ,it means that to make a slice of it;but in the second statement,the for statement ues 'a' directly ,so cause a bad result </font><br /><br /><strong><font size="2">Note Three: Compare for efficiency<br /></font></strong><br /><font size="2">str_test = []<br /># method one :<br />str_test.append('attach')<br />#method two:<br />str_test = str_test + ['attach']<br /><br />The Two method above has the same function ,but the more efficient one is the first one<br /> <br /></font><font size="2"><strong>Note Four :about Defining Functions <br /></strong><u>Form 1:Default Argument Values</u><br />The default value is evaluated only once.<br /></font><font face="Arial" size="2">def f(a, L=[]):<br />    L.append(a)<br />    return L<br /><br />print f(1)<br />print f(2)<br />print f(3)</font></p><p><font size="2">This will print </font></p><p><font size="2"></font></p><div class="verbatim"><pre><font face="Arial" size="2">[1]
[1, 2]
[1, 2, 3]
</font></pre></div><p><font size="2">If you don't want the default to be shared between subsequent calls, you can write the function like this instead: </font></p><p><font size="2"></font></p><div class="verbatim"><pre><font face="Arial" size="2">def f(a, L=None):
    if L is None:
        L = []
    L.append(a)
    return L<br /><br /><u>Form 2 : Keyword Arguments</u><br /></font><p><font face="Arial" size="2">When a final formal parameter of the form  <em>**name</em>  is present, it receives a </font><a class="ulink" href="http://www.python.org/doc/lib/typesmapping.html"><font face="Arial" color="#002c99" size="2">dictionary</font></a><font face="Arial" size="2"> containing all keyword arguments except<br /> for those corresponding to a formal parameter. This may be combined with a formal parameter of the form *name (described in <br />the next subsection) which receives a tuple containing the positional arguments beyond the formal parameter list. <em>(*name</em> must<br /> occur before <em>**name</em>) For example, if we define a function like this: </font></p><p><font face="Arial" size="2"></font></p><div class="verbatim"><pre><font face="Arial" size="2"><em>def cheeseshop(kind, *arguments, **keywords):
    print "-- Do you have any", kind, '?'
    print "-- I'm sorry, we're all out of", kind
    for arg in arguments: print arg
    print '-'*40<br />    keys = keywords.keys()
    keys.sort()
    for kw in keys: print kw, ':', keywords[kw]</em></font></pre></div><p><font face="Arial" size="2">It could be called like this: </font></p><p><font face="Arial" size="2"></font></p><div class="verbatim"><pre><font face="Arial" size="2"><em>cheeseshop('Limburger', "It's very runny, sir.",
           "It's really very, VERY runny, sir.",
           client='John Cleese',
           shopkeeper='Michael Palin',
           sketch='Cheese Shop Sketch')</em></font></pre></div><p><font face="Arial" size="2">and of course it would print: </font></p><p><font face="Arial" size="2"></font></p><div class="verbatim"><pre><font face="Arial" size="2"><em>-- Do you have any Limburger ?
-- I'm sorry, we're all out of Limburger
It's very runny, sir.
It's really very, VERY runny, sir.
----------------------------------------
client : John Cleese
shopkeeper : Michael Palin
sketch : Cheese Shop Sketch</em></font></pre></div><p><font face="Arial" size="2">Note that the <em>sort()</em> method of the list of keyword argument names is called before printing the contents of the <em> keywords<br /></em>dictionary; if this is not done, the order in which the arguments are printed is undefined. </font></p><font size="3"></font></pre></div></font><img src ="http://www.cppblog.com/Jeff-Chen/aggbug/5441.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.cppblog.com/Jeff-Chen/" target="_blank">Jeff-Chen</a> 2006-04-13 10:50 <a href="http://www.cppblog.com/Jeff-Chen/archive/2006/04/13/5441.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item><item><title>Python 学习之路（一）</title><link>http://www.cppblog.com/Jeff-Chen/archive/2006/04/12/5413.html</link><dc:creator>Jeff-Chen</dc:creator><author>Jeff-Chen</author><pubDate>Wed, 12 Apr 2006 11:00:00 GMT</pubDate><guid>http://www.cppblog.com/Jeff-Chen/archive/2006/04/12/5413.html</guid><wfw:comment>http://www.cppblog.com/Jeff-Chen/comments/5413.html</wfw:comment><comments>http://www.cppblog.com/Jeff-Chen/archive/2006/04/12/5413.html#Feedback</comments><slash:comments>0</slash:comments><wfw:commentRss>http://www.cppblog.com/Jeff-Chen/comments/commentRss/5413.html</wfw:commentRss><trackback:ping>http://www.cppblog.com/Jeff-Chen/services/trackbacks/5413.html</trackback:ping><description><![CDATA[
		<strong>
				<font face="Arial" size="2">Python读书笔记( 2006-4-12 )：</font>
				<br />
				<br />
		</strong>
		<font face="Tahoma">
				<font size="2">
						<strong>Note One   : about integer and long integer</strong>
						<br />There are four types of numeric literals: plain integers, long integers, floating point numbers, and imaginary numbers. There are no complex literals (complex numbers can be formed by adding a real number and an imaginary number). <br /></font>
		</font>
		<font face="Tahoma">
				<font size="2">Note that numeric literals do not include a sign; a phrase like <code>-1</code> is actually an expression composed of the unary operator `<code>-</code>' and the literal 1<br /><br /></font>
				<strong>
						<font size="2">Note Two   : about operators<br /></font>
				</strong>
		</font>
		<font face="Tahoma">
				<font size="2">The comparison operators <code>&lt;&gt;</code> and <code>!=</code> are alternate spellings of the same operator. <code>!=</code> is the preferred spelling; <code>&lt;&gt;</code> is obsolescent. <br /><br /></font>
				<font size="2">
						<strong>Note Three: about delimiters<br /></strong>The following printing ASCII characters are not used in Python. Their occurrence outside string literals and comments is an unconditional error:   $       ?<br /><br /></font>
				<font size="2">
						<strong>Note Four  : about <strong>Sequences</strong><br /></strong>Sequences also support slicing: <font face="Arial">a[i:j] </font>selects all items with index <var>k</var> such that  i &lt;= k &lt; j  When used as an expression, a slice is a sequence of the same type. This implies that the index set is renumbered so that it starts at 0. Some sequences also support ``extended slicing'' with a third ``step'' parameter: <em><font face="Courier New">a[i:j:k]</font></em> selects all items of <var>a</var> with index <var>x</var> where  x = i +n*k , n &gt;= 0 <var></var> and i &lt;= x &lt; j.</font>
		</font>
		<font size="2">
				<br />
				<br />
		</font>
		<font size="2">
				<font face="Arial">
						<strong>Note Five   : about Primary Prompt<br /></strong>
				</font>
				<font face="Tahoma">In interactive mode, the last printed expression is assigned to the variable <font face="Tahoma"><code>_</code>. This means that when you are using Python as a desk calculator, it is somewhat easier to continue calculations, for example: <br /></font><font face="Tahoma"><br />&gt;&gt;&gt; tax = 12.5 / 100<br />&gt;&gt;&gt; price = 100.50<br />&gt;&gt;&gt; price * tax<br />12.5625<br />&gt;&gt;&gt; price + _<br />113.0625<br />&gt;&gt;&gt; round(_, 2)<br />113.06<br />&gt;&gt;&gt;<br /></font><br />This variable should be treated as read-only by the user. Don't explicitly assign a value to it -- you would create an independent local variable with the same name masking the built-in variable with its magic behavior. </font>
		</font>
<img src ="http://www.cppblog.com/Jeff-Chen/aggbug/5413.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.cppblog.com/Jeff-Chen/" target="_blank">Jeff-Chen</a> 2006-04-12 19:00 <a href="http://www.cppblog.com/Jeff-Chen/archive/2006/04/12/5413.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item><item><title>初识 python!</title><link>http://www.cppblog.com/Jeff-Chen/archive/2006/04/12/5411.html</link><dc:creator>Jeff-Chen</dc:creator><author>Jeff-Chen</author><pubDate>Wed, 12 Apr 2006 10:14:00 GMT</pubDate><guid>http://www.cppblog.com/Jeff-Chen/archive/2006/04/12/5411.html</guid><wfw:comment>http://www.cppblog.com/Jeff-Chen/comments/5411.html</wfw:comment><comments>http://www.cppblog.com/Jeff-Chen/archive/2006/04/12/5411.html#Feedback</comments><slash:comments>2</slash:comments><wfw:commentRss>http://www.cppblog.com/Jeff-Chen/comments/commentRss/5411.html</wfw:commentRss><trackback:ping>http://www.cppblog.com/Jeff-Chen/services/trackbacks/5411.html</trackback:ping><description><![CDATA[
		<p>
				<font size="2">
						<font face="Arial">
								<strong>与python第一次亲密接触!</strong>
								<br />在网上搜集了很多资料和浏览了python的很多相关文章，它给我的总体感觉是在文本处理上的高效和语言的"人性化",<br />面举个例子来说明我为什么觉得"人性化":</font>
				</font>
		</p>
		<p>
				<font size="2">
						<font face="Tahoma">
								<strong>1. Reason One : </strong> <font face="Arial">长整型无长度限制，除了电脑硬件的限制<br /></font>Although both lower case "<tt class="character">l</tt>" and upper case "<tt class="character">L</tt>" are allowed as suffix for long integers, it is strongly recommended to always use "<tt class="character">L</tt>", since the letter "<tt class="character">l</tt>" looks too much like the digit "<tt class="character">1</tt>". <br /></font>
						<font face="Tahoma">Plain integer literals that are above the largest representable plain integer (e.g., 2147483647 when using 32-bit arithmetic) are accepted as if they were long integers instead.</font>
				</font>
				<font face="Tahoma" size="2">There is no limit for long integer literals apart from what can be stored in available memory. </font>
				<font face="Tahoma" size="2">Some examples of plain integer literals (first row) and long integer literals (second and third rows): </font>      <font face="Tahoma"><br /><font size="2">7      2147483647                                      0177<br />3L    79228162514264337593543950336L    0377L   0x100000000L<br />       79228162514264337593543950336                 0xdeadbeef</font><br /></font><br /></p>
		<p>
				<strong>
						<font face="Tahoma" size="2">2. Reason Two : (quote) </font>
				</strong>
				<font face="Tahoma">
						<font size="2">
								<font face="Arial">一个python小tip，交换两个变量的值，而且不使用第三个变量： <br />&gt;&gt;&gt; a,b = 1,2 <br />&gt;&gt;&gt; a,b = b,a <br />&gt;&gt;&gt; a,b <br />(2, 1) <br />&gt;&gt;&gt; <br /></font>
								<br />
								<font face="Arial">
										<strong>3.Reason Three: <br /></strong>它是用C语言开发的，但是效率比起C语言也差了多少，当然没C快啦，但是他里面的很多函数非常方便，功能比C强大很多。<br /><strong>4.Reason Four :　<br /></strong>最让人兴奋的原因就是BitComet就是它开发出来的。<br /><br /></font>
						</font>
						<font size="2">
								<font face="Arial">他避免了很多初学程序设计时常常出现的问题，尽管对于大多数人来说都是几乎不会发生的，但是从这点可以看出它对它的用户是傻瓜开始的。因为傻瓜才会犯哪些错误！<br /><br /></font>
								<strong> </strong> </font>
				</font>
				<font size="2">
				</font>
				<br />
				<br />
		</p>
<img src ="http://www.cppblog.com/Jeff-Chen/aggbug/5411.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.cppblog.com/Jeff-Chen/" target="_blank">Jeff-Chen</a> 2006-04-12 18:14 <a href="http://www.cppblog.com/Jeff-Chen/archive/2006/04/12/5411.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item></channel></rss>