??xml version="1.0" encoding="utf-8" standalone="yes"?>久久99热精品,理论片午午伦夜理片久久,久久精品a亚洲国产v高清不卡 http://www.shnenglu.com/Jeff-Chen/category/1412.htmlzh-cnMon, 26 May 2008 12:07:21 GMTMon, 26 May 2008 12:07:21 GMT60python的对象与名字l定Q{_(d)此文甚好,U字部分为经典说明)(j)http://www.shnenglu.com/Jeff-Chen/archive/2006/04/17/5785.htmlJeff-ChenJeff-ChenMon, 17 Apr 2006 11:27:00 GMThttp://www.shnenglu.com/Jeff-Chen/archive/2006/04/17/5785.htmlhttp://www.shnenglu.com/Jeff-Chen/comments/5785.htmlhttp://www.shnenglu.com/Jeff-Chen/archive/2006/04/17/5785.html#Feedback0http://www.shnenglu.com/Jeff-Chen/comments/commentRss/5785.htmlhttp://www.shnenglu.com/Jeff-Chen/services/trackbacks/5785.html

python的对象与名字l定Q{_(d)此文甚好Q?/a>

i = 1

  q是一个再单不q的赋D句,即便是才开始学?fn)编E的新手也能脱口而出它的含义 -- “设|变量i的gؓ(f)1”?/p>

i = 2

  “将变量i的值改?”,当看到接下来q行代码Ӟ你脑中肯定?x)立xQ现这L(fng)念头?/p>

  q难道会(x)有问题嘛Q这单单的一行赋D句其实包含了(jin)python中的三个重要概念Q名字、绑定和对象?br />python对赋D句作Z(jin)自己的定义:(x)
  “符D句是用来名字绑定(或重新绑定)(j)到某个对象的操作Q而且它也可用来修改可变对象的属性或
对象中所包含的成员。?/p>

  名字l定到对象这个概念在python中随处可见,可以说是python的最基本而且最重要的概念之一。如?br />没有很好理解q一点,一些意想不到的l果׃(x)在?zhn)的代码中?zhn)然出现?/p>

  先来看一个简单例子:(x)

>>> a = {'g':1}
>>> b = a*4
>>> print b
[{'g': 1}, {'g': 1}, {'g': 1}, {'g': 1}]
>>> b[0]['g'] = 2
>>> print b

  Z意料嘛?h慢看完这文章?/p>

1. 对象
  “万物皆对象?Everything is object)Q这是pythonq种面向对象语言所倡导的理c(din)在我们熟?zhn)的C++中,1只是一个整型数Q而不是一个对象。但在python中,1却是一个实实在在的对象Q?zhn)可以用dir(1)来显C它的属性?/p>

  在python中,所有对象都有下面三个特征:(x)
 * 唯一的标识码(identity)
 * cd
 * 内容Q或UCؓ(f)|(j)

  一旦对象被创徏Q它的标识码׃允许更改。对象的标识码可以有内徏函数id()获取Q它是一个整型数。?zhn)可以它惌对象在内存中的地址Q其实在目前的实C标识码也是该对象的内存地址?/p>

>>> class c1:
 pass
...
>>> obj = c1()
>>> obj
<__main__.c1 instance at 0x00AC0738>
>>> id(obj)
11274040

  换算一下,11274040是十六q制?x00AC0738?/p>

>>> id(1)
7957136

  q就是前面提到的1q个对象的标识码Q也是它在内存中的地址?/font>

  当用is操作W比较两个对象时Q就是在比较它们的标识码。更切地说Qis操作W是在判断两个对象是否是同一个对象?br />>>> [1] is [1]
  其结果是FalseQ是因ؓ(f)q是两个不同的对象,存储在内存中的不同地斏V?/font>

>>> [1] == [1]
  其结果是TrueQ是因ؓ(f)q两个不同的对象有着相同的倹{?/font>

  与对象的标识码类|对象的类型也是不可更改的。可以用内徏函数type()取得对象的类型?/p>

  有的对象的值是可以改变的,q类对象叫作可变对象Q而另外一些对象在创徏后其值是不可改变的(?q个对象Q,q类对象叫作恒定对象。对象的可变性是由它的类型决定的Q比如数值型(number)、字W串?string)以及(qing)序列?tuple)的对象是恒定对象Q而字典型(dictionary)和列表型(list)的对象是可变对象?/p>

  除了(jin)上面提到的三个特征外Q一个对象可能:(x)
 * 没有或者拥有多个方?br /> * 没有或者有多个名字

2. 名字
  名字是对一个对象的U呼Q一个对象可以只有一个名字,也可以没有名字或取多个名字。但对象自己却不知道有多名字,叫什么,只有名字本n知道它所指向的是个什么对象。给对象取一个名字的操作叫作命名Qpython赋D句认为是一个命名操作(或者称为名字绑定)(j)?/p>

  名字在一定的名字I间内有效,而且唯一Q不可能在同一个名字空间内有两个或更多的对象取同一名字?/p>

  让我们再来看看本的W一个例子:(x)i = 1。在python中,它有如下两个含义Q?br /> * 创徏一个gؓ(f)1的整型对?br /> * "i"是指向该整型对象的名字(而且它是一个引用)(j)
 
3. l定
  如上所讲的Q绑定就是将一个对象与一个名字联pv来。更切地讲Q就是增加该对象的引用计数。众所周知QC++中一大问题就是内存泄?-- 卛_态分配的内存没有能够回收Q而解册一问题的利器之一是引用计数。python采用了(jin)q一技术实现其垃圾回收机制?br /> 
  python中的所有对象都有引用计数?/p>

i=i+1

* q创Z(jin)一个新的对象,其gؓ(f)i+1?br />* "i"q个名字指向?jin)该新徏的对象,该对象的引用计数加一Q?i"以前所指向的老对象的
  引用计数减一?br />* "i"所指向的老对象的值ƈ没有改变?br />* q就是ؓ(f)什么在python中没?+?-q样的单目运符的一个原因?/p>

3.1 引用计数
  对象的引用计数在下列情况下会(x)增加Q?br /> * 赋值操?br /> * 在一个容器(列表Q序列,字典{等Q中包含该对?/p>

  对象的引用计数在下列情况下会(x)减少Q?br /> * d?jin)当前的名字I间Q该名字I间中的本地名字都会(x)被销毁)(j)
 * 对象的一个名字被l定到另外一个对?br /> * 对象从包含它的容器中U除
 * 名字被显C地用del销毁(如:(x)del iQ?/p>

  当对象的引用计数降到0后,该对象就?x)被销毁,其所占的内存也就得以回收?/p>

4. 名字l定所带来的一些奇特现?/p>

?.1Q?br />>>> li1 = [7, 8, 9, 10]
>>> li2 = li1
>>> li1[1] = 16
>>> print li2
[7, 16, 9, 10]

注解Q这里li1与li2都指向同一个列表对象[7, 8, 9, 10]Q“li[1] = 16”是改变该列表中的第2个元素,所以通过li2时同样会(x)看到q一改动?/p>

?.2Q?br />>>> b = [{'g':1}]*4
>>> print b
[{'g': 1}, {'g': 1}, {'g': 1}, {'g': 1}]
>>> b[0]['g'] = 2
>>> print b
[{'g': 2}, {'g': 2}, {'g': 2}, {'g': 2}]

?.3Q?br /> >>> b = [{'g':1}] + [{'g':1}] + [{'g':1}] + [{'g':1}]
>>> print b
[{'g': 1}, {'g': 1}, {'g': 1}, {'g': 1}]
>>> b[0]['g'] = 2
>>> print b
[{'g': 2}, {'g': 1}, {'g': 1}, {'g': 1}]

注解Q在有的python书中讲到乘法W号Q?Q就相当于几个加法的重复Q即认ؓ(f)?.2应该?.3的结果一致?br />      其实不然。例4.2中的bq个列表中的每一个元素{'g': 1}其实都是同一个对象,可以用id(b[n])q行验证。而例4.3中则是四个不同的对象。我们可以采用名字绑定的Ҏ(gu)消除q一歧义Q?/font>

>>> a = {'g' : 1}
>>> b = [a]*4
>>> b[0]['g'] = 2
>>> print b
[{'g': 2}, {'g': 2}, {'g': 2}, {'g': 2}]
>>> print a
{'g': 2}

>>> a = {'g' : 1}
>>> b = [a] + [a] + [a] + [a]
>>> b[0]['g'] = 2
>>> print b
[{'g': 2}, {'g': 2}, {'g': 2}, {'g': 2}]
>>> print a
{'g': 2}

  不过对于恒定对象而言Q?”和q箋加法的效果一栗比如,b=[1] * 4 q同于 b=[1]+[1]+[1]+[1]?/p>

5. 函数的传参问?br />  函数的参C递也是一个名字与对象的绑定过E,而且是绑定到另外一个名字空_(d)卛_C内部的名字空_(d)(j)。python对赋D句的独特看法又会(x)对函数的传递造成什么媄(jing)响呢Q?/p>

5.1 传|传址Q?br />  在学?fn)C++的时候我们都知道有两U参C递方式:(x)传值和传址。而在python中所有的参数传递都是引用传递(pass referenceQ,也就是传址。这是由于名字是对象的一个引用这一python的特性而自然得来的Q在函数体内部对某一外部可变对象作了(jin)修改肯定?x)将其改变带到函C外。让我们来看看下?br />q个例子Q?/p>

?.1
>>> a = [1, 2, 3]
>>> def foo(par):
... par[1] = 10
...
>>> foo(a)
>>> print a
[1, 10, 3]

  因此Q在python中,我们应该抛开传递参数这U概念,时刻牢记函数的调用参数是对象用另外一个名字空间的名字l定。在函数中,不过是用?jin)另外一个名字,但还是对q同一个对象进行操作?/p>

5.2 ~省参数
  使用~省参数Q是我们喜爱的一U作法。这可以在调用该函数时节省不的击键ơ数Q而且代码也显得更加简z。更重要的是它从某种意义上体C(jin)q个函数设计的初街?br />  但是python中的~省参数Q却隐藏着一个玄机,初学者肯定会(x)在上面栽跟头Q而且q个错误非常隐秘。先看看下面q个例子Q?/p>

?.2
>>> def foo(par=[]):
... par.append(0)
... print par
... 
>>> foo()                       # W一ơ调?br />[0]
>>> foo()                       # W二ơ调?br />[0, 0]

  Z(jin)什么问题?q个参数par好像cM与C中的?rn)态变量,累计?jin)以前的l果。是q样吗?当然不是Q这都是“对象、名字、绑定”这些思想惹的“祸”。“万物皆对象”,q记得吗Q这里,函数foo当然也是一个对象,可以UC为函数对象(与一般的对象没什么不同)(j)。先来看看这个对象有些什么属性?/p>

>>> dir(foo)
['__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']

  单从名字上看Q“func_defaults”很可能与缺省参数有养I看看它的倹{?/p>

>>> foo.func_defaults          # 昄q个属性的内容
([0, 0],)
>>> foo()                      # W三ơ调?br />[0, 0, 0]
>>> foo.func_defaults          # 再来看看q个属?br />([0, 0, 0],)

  果不其然Q就是这个序列对象(tuple)包含?jin)所有的~省参数。验证一下:(x)

>>> def fooM(par1, def1=1, def2=[], def3='str'):           # 定义一个有多个~省参数的函?br />... def2.append(0)
... print par1, def1, def2, def3
...
>>> fooM.func_defaults
(1, [], 'str')

  在函数定义中有几个缺省参敎ͼfunc_defaults中就?x)包括几个对象,暂且UC为缺省参数对象(如上列中?Q[]?str'Q。这些缺省参数对象的生命周期与函数对象相同,从函C用def定义开始,直到其消亡(如用delQ。所以即便是在这些函数没有被调用的时候,但只要定义了(jin)Q缺省参数对象就?x)一直存在?/p>

  前面讲过Q函数调用的q程是对象在另外一个名字空间的l定q程。当在每ơ函数调用时Q如果没有传递Q何参数给q个~省参数Q那么这个缺省参数的名字׃(x)l定到在func_defaults中一个对应的~省参数对象上?br />>>> fooM(2)
  函数fooM内的名字def1׃(x)l定到func_defaults中的W一个对象,def2l定到第二个Qdef3则是W三个?br />所以我们看到在函数foo中出现的累加现象Q就是由于parl定到缺省参数对象上Q而且它是一个可变对象(列表Q,par.append(0)׃(x)每次改变q个~省参数对象的内宏V?/p>

  函数foo改进一下,可能?x)更?gu)帮助理解Q?br />>>> def foo(par=[]):
... print id(par)                  # 查看该对象的标识?br />... par.append(0)
... print par
...
>>> foo.func_defaults                  # ~省参数对象的初始?br />([],)
>>> id(foo.func_defaults[0])           # 查看W一个缺省参数对象的标识?br />11279792                               # 你的l果可能?x)不?br />>>> foo()                               
11279792                               # 证明parl定的对象就是第一个缺省参数对?br />[0]
>>> foo()
11279792                               # 依旧l定到第一个缺省参数对?br />[0, 0]                                 # 该对象的值发生了(jin)变化
>>> b=[1]
>>> id(b)
11279952
>>> foo(b)                             # 不用缺省参?br />11279952                               # 名字par所l定的对象与外部名字b所l定的是同一个对?br />[1, 0]
>>> foo.func_defaults
([0, 0],)                              # ~省参数对象q在那里Q而且值ƈ没有发生变化
>>> foo()                   
11279792                               # 名字par又绑定到~省参数对象?br />([0, 0, 0],)

  Z(jin)预防此类“问题”的发生Qpython采用下列Ҏ(gu)Q?br />>>> def foo(par=[]):
... if par is None:
...  par = []
... par.append(0)
... print par

  使用None作ؓ(f)哨兵Q以判断是否有参C入,如果没有Q就新创Z个新的列表对象,而不是绑定到~省
参数对象上?/p>

6.ȝ
  * python是一U纯_的面向对象语言?br />  * 赋D句是名字和对象的l定q程?br />  * 函数的传参是对象C同名字空间的l定?/p>

7.参考资?br />  * 《Dive Into Python》,Mark PilgrimQ?a >http://diveintopython.org, 2003?br />  * 《Python Objects》,Fredrik LundhQ?a >http://www.effbot.org/zone/python-objects.htm?br />  * 《An Introduction to Python》,David M. BeazleyQ?a >http://systems.cs.uchicago.edu/~beazley/tutorial/beazley_intro_python/intropy.pdf?br />  *  从Python官方|站Q?a >http://www.python.orgQ上可以?jin)解到所有关于Python的知识?br />

posted on 2005-06-25 10:41 I love linux 阅读(670) 评论(2)  ~辑 收藏收藏?65Key 所属分c? Python

评论

re: python的对象与名字l定Q{_(d)此文甚好Q?2005-12-28 16:43 jarodzz

因此Q在python中,我们应该抛开传递参数这U概念,时刻牢记函数的调用参数是对象用另外一个名字空间的名字l定。在函数中,不过是用?jin)另外一个名字,但还是对q同一个对象进行操作?

def foolyou(a):
a=a+1

if __name__=='__main__':
b=1
foolyou(b)
print b

what is b now?  回复  

re: python的对象与名字l定Q{_(d)此文甚好Q?a name="Post">2006-01-04 16:15 asdf_asdf

a=a+1 已经是另一?引用"?
>>> def foolyou(a):
print id(a)
a=a+1
print id(a)

>>> b
1
>>> foolyou(b)
148479408
148479396
>>> id(b)
148479408  回复  



Jeff-Chen 2006-04-17 19:27 发表评论
]]>
The most classical topic for Python noviceshttp://www.shnenglu.com/Jeff-Chen/archive/2006/04/16/5651.htmlJeff-ChenJeff-ChenSun, 16 Apr 2006 08:58:00 GMThttp://www.shnenglu.com/Jeff-Chen/archive/2006/04/16/5651.htmlhttp://www.shnenglu.com/Jeff-Chen/comments/5651.htmlhttp://www.shnenglu.com/Jeff-Chen/archive/2006/04/16/5651.html#Feedback0http://www.shnenglu.com/Jeff-Chen/comments/commentRss/5651.htmlhttp://www.shnenglu.com/Jeff-Chen/services/trackbacks/5651.html阅读全文

Jeff-Chen 2006-04-16 16:58 发表评论
]]>
Python 学习(fn)之\Q提高ȝQ?/title><link>http://www.shnenglu.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.shnenglu.com/Jeff-Chen/archive/2006/04/15/5611.html</guid><wfw:comment>http://www.shnenglu.com/Jeff-Chen/comments/5611.html</wfw:comment><comments>http://www.shnenglu.com/Jeff-Chen/archive/2006/04/15/5611.html#Feedback</comments><slash:comments>0</slash:comments><wfw:commentRss>http://www.shnenglu.com/Jeff-Chen/comments/commentRss/5611.html</wfw:commentRss><trackback:ping>http://www.shnenglu.com/Jeff-Chen/services/trackbacks/5611.html</trackback:ping><description><![CDATA[ <strong>Note One Q?Lists Comprehensions<br /></strong>[3*x for x in vec if x > 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 />>>> test_str = '   I Love Python  '<br />>>> 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 />>>> num_1 = 3.14<br />>>> num_2 = 0.618<br />>>> str(num_1) , str(num_2)<br />'3.14' '0.618'<br /><strong>3.dict()</strong><br />dict() -> new empty dictionary.<br />dict(mapping) -> new dictionary initialized from a mapping object's<br />    (key, value) pairs.<br />dict(seq) -> new dictionary initialized as if via:<br />    d = {}<br />    for k, v in seq:<br />        d[k] = v<br />dict(**kwargs) -> 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 />>>> 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>>>> questions = ['name', 'quest', 'favorite color'] >>> answers = ['lancelot', 'the holy grail', 'blue'] >>> 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>>>> basket = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana'] >>> 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 id="zzfbiti" 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 id="viklund" 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 id="fgrhxrl" 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 id="ardafhb" 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 id="iqbghxc" 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.shnenglu.com/Jeff-Chen/aggbug/5611.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.shnenglu.com/Jeff-Chen/" target="_blank">Jeff-Chen</a> 2006-04-15 13:13 <a href="http://www.shnenglu.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 Trickshttp://www.shnenglu.com/Jeff-Chen/archive/2006/04/14/5535.htmlJeff-ChenJeff-ChenFri, 14 Apr 2006 05:27:00 GMThttp://www.shnenglu.com/Jeff-Chen/archive/2006/04/14/5535.htmlhttp://www.shnenglu.com/Jeff-Chen/comments/5535.htmlhttp://www.shnenglu.com/Jeff-Chen/archive/2006/04/14/5535.html#Feedback0http://www.shnenglu.com/Jeff-Chen/comments/commentRss/5535.htmlhttp://www.shnenglu.com/Jeff-Chen/services/trackbacks/5535.html

Jeff-Chen 2006-04-14 13:27 发表评论
]]>
无法在eclipse中更新pydevQ供遇到此类问题的朋友参考)(j)http://www.shnenglu.com/Jeff-Chen/archive/2006/04/14/5525.htmlJeff-ChenJeff-ChenFri, 14 Apr 2006 04:00:00 GMThttp://www.shnenglu.com/Jeff-Chen/archive/2006/04/14/5525.htmlhttp://www.shnenglu.com/Jeff-Chen/comments/5525.htmlhttp://www.shnenglu.com/Jeff-Chen/archive/2006/04/14/5525.html#Feedback0http://www.shnenglu.com/Jeff-Chen/comments/commentRss/5525.htmlhttp://www.shnenglu.com/Jeff-Chen/services/trackbacks/5525.html 头疼?jin)很?eclipse中无法正常更新pydev。我又回头检查,域名是正的Q但是还是出现错误?br />想了(jin)很久Q在|上到处扑օ于此c问题的文章Q但是收获不大,可以说几乎找不到之类文章?br />q运的事 Q我正在L其他插g时候和察看其他python开发工L(fng)时候,无意中点Z(jin)IBM 的下面这个页面?br />时我就恍然大?zhn)Q才发现无法更新的原因:(x)
因ؓ(f)公司的封掉了(jin)几个端口Q防止用非工作范围内的׃软g或其他的聊天软gQ?br />而eclipse的更新模式基于基于FTP模式的?br />当然q是造成无法更新的原因之一Q可能还有其他原因但是我没想刎ͼ也没遇见q?br />
quote:

下蝲Ҏ(gu)QFTP、HTTP 和下载助?/span>
 

IBM developerWorks 提供?jin)三U下载方法:(x)FTP、HTTP 以及(qing)用于大文件下载的下蝲助手Q?Download DirectorQ。大多数情况下,FTP 要比 HTTP 更可靠,q可~短下蝲旉。最新的览器在q行 FTP 下蝲时会(x)昄旉估计和传输速度。在有些情况下,览器还可以l传中断?FTP 下蝲。要利用 FTP 的这U方便性,在?HTTP 下蝲之前首先试一?FTP 下蝲方式?/p>

如果(zhn)?FTP I过防火墙下载时遇到?jin)问题,再试?HTTP 下蝲。虽然?HTTP 方式q行大文件下载时不如 FTP 可靠Q但 Internet Explorer 5.01 ?qing)以上版本有时能够恢复中断?HTTP 下蝲。HTTP 下蝲能够I过防火墙,因ؓ(f)它用了(jin)端口?80 来进行数据传输。以下下载行为和错误可能是遇C(jin)防火墙问题:(x)

  • 临近l束但又没有完成时下载突然停止?
  • 每次在同一地方停止下蝲?
  • 错误 400 表示代理加蝲p|?
  • 出现一条消息表明文件类型未扑ֈ?
  • 出现一条消息表明页面已l移走?


Jeff-Chen 2006-04-14 12:00 发表评论
]]>
?Eclipse ?Ant q行 Python 开?/title><link>http://www.shnenglu.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.shnenglu.com/Jeff-Chen/archive/2006/04/14/5521.html</guid><wfw:comment>http://www.shnenglu.com/Jeff-Chen/comments/5521.html</wfw:comment><comments>http://www.shnenglu.com/Jeff-Chen/archive/2006/04/14/5521.html#Feedback</comments><slash:comments>1</slash:comments><wfw:commentRss>http://www.shnenglu.com/Jeff-Chen/comments/commentRss/5521.html</wfw:commentRss><trackback:ping>http://www.shnenglu.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 q行 Python 开?/h1> <p id="subtitle">?Eclipse IDE ?Apache Ant 构徏工具q行 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 是一U非常灵zd大的动态脚本编E语aQ具有完整的面向对象Ҏ(gu)。本文着重介l了(jin)如何使用Z Java 技术的行开发工?Eclipse ?Ant q行 Python 开发? name="body" /> <input type="hidden" value="?Eclipse ?Ant q行 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="http://www.ibm.com/i/c.gif" width="8" height="1" alt=""/></td><td width="16"><img src="http://www.ibm.com/i/v14/icons/em.gif" height="16" width="16" vspace="3" alt="此作为电(sh)子邮件发? /></td><td width="122"><p><a class="smallplainlink" href="javascript:document.email.submit();"><b>此作为电(sh)子邮件发?/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="此作为电(sh)子邮件发? 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">此作为电(sh)子邮件发?/font> </b> </a> </p> </td> </tr> <noscript> <tr valign="top"> <td width="8"> <img alt="" height="1" width="8" src="http://www.ibm.com/i/c.gif" /> </td> <td width="16"> <img alt="" width="16" height="16" src="http://www.ibm.com/i/c.gif" /> </td> <td class="small" width="122"> <p> <span id="zmrbclf" class="ast">未显C需?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" > <font color="#5c81a7" size="2">Java 应用开发源动力 Q?下蝲免费软gQ快速启动开?/font> </a> </p> </td> </tr> </tbody> </table> </td> </tr> </tbody> </table> <!--END RESERVED FOR FUTURE USE INCLUDE FILES--> <br /> </td> </tr> </tbody> </table> <p>U别: 初</p> <p> <a > <font color="#996699">Ron Smith</font> </a>, 负责?br /></p> <p>2004 q?6 ?01 ?/p> <blockquote>Python 是一U非常灵zd大的动态脚本编E语aQ具有完整的面向对象Ҏ(gu)。众多的支持者指出,Python 语言与其他语a相比能更快更有效地表辑և他们的意图。但是从 Java 技术™ ?Microsoft] .NET 刚刚转到 Python 的h?x)发玎ͼ功能丰富而精致的 IDE 和开发工具都不见?jin)。那些开发h员可以从他们熟?zhn)?Java 开发工具中扑ֈ解决Ҏ(gu)。本文着重介l了(jin)如何使用Z Java 技术的行开发工?Eclipse ?Ant q行 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 id="tvhinhb" class="atitle"> <font face="Arial" size="4">?/font> </span> </a> </p> <p>多年以来Q?Java 语言?Python 阵营之间一直存在大量的异花授粉现象。在q方面作出突?gu)率的可能?Jython。这是一个纯_用 Java 实现?Python q行时环境。按照这一说法Q?zhn)研I如何用 Eclipse IDE ?Ant 构徏与部|工具实?Python 开发。Eclipse ?Ant 是非常流行的工具Q它们特性丰富、可扩展性强、而且开放源代码QPython 也具有相同的品质。PyDev ?PyAntTasks 分别?Eclipse ?Ant 的扩展,有了(jin)它们可能用q些 Java 工具开?Python。本文从下蝲安装所需的工具与扩展开始讲赗ؓ(f)?jin)解释如何?Python 开发中使用 Eclipse ?AntQ我用实际?Python 代码例子d RSS 资源?</p> <p>本文不会(x)涉及(qing) Eclipse、Ant、Python 的细节。有兌些话题的深入讨论Q请参阅 <a ><font color="#996699">参考资?/font></a> 一节中的链接?</p> <p> <a name="N1004D"> <span id="acahrpn" class="smalltitle"> <strong> <font face="Arial">Python 支持情况</font> </strong> </span> </a> </p> <p>本文用到的Y仉?CPython 2.3 下测试过。除?jin)几个异常情况之外,应该也能?Jython 中运行。特别需要指出,PyDev 调试器目前不支持 Jython。另一个区别是通过 Jython 执行的脚本在?PyDev 中运行之后就转入交互模式Q这样就必须手动杀歅RPyDev ~辑器与 Jython 的源代码兼容QPython Ant d?py-doc d之外也和 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" > <b> <font color="#996699">回页?/font> </b> </a> </td> </tr> </tbody> </table> </td> </tr> </tbody> </table> <br /> <br /> <p> <a name="N10056"> <span id="vuvlmre" class="atitle"> <font face="Arial" size="4">使用 Eclipse q行 Python 开?/font> </span> </a> </p> <p> <a name="N1005C"> <span id="ultnsxg" class="smalltitle"> <strong> <font face="Arial">Eclipse 概述</font> </strong> </span> </a> </p> <p>Eclipse 是一?Java 技术集成开发环境,?IBM 开发,q开攑օ源代码。它?IBM 商业软g WebSphere Application Development 环境以及(qing)其他多种工具的基。Eclipse 的开发社区非常活跃,他们不仅开?Eclipse 本nQ还开发大量的插g?Eclipse 使用。有?Eclispe ?Eclipse 插g?Web 站点Q请参阅 <a ><font color="#996699">参考资?/font></a> 一节中的链接。尽从传统上讲 Eclipse 是一U?Java 开发工P但是一些插件的存在使得?Eclipse 中开发其他语a的程序成为可能,?C/C++、Python ?Perl?</p> <p>?Eclipse 中,源代码被l织到项目(projectQ中。项目可以加载、卸载和导入。Eclipse 用户界面的结构划分ؓ(f)视图QViewQ与~辑器(EditorQ。视图与~辑器的例子包括Q源代码大纲视图、Java 源代码编辑器、Python 源代码编辑器和文件系l导航视图。Eclipse 用户界面中最关键的隐含概念就?<i>视角QperspectiveQ?/i>。视角是通常在执行某U类型活动时一起用的一l视图。Eclipse 中的标准视角包括QDebug、Java Browsing、Java、Java Type Hierarchy、Plug-in Development、CVS Repository Exploring、Resource ?Install/Update。目前还不存在单独的 Python 视角。在q行 Python 开发时Q我通常使用 Resource 视角?Debug 视角?</p> <p> <a name="N1006F"> <span id="wyrhxvp" class="smalltitle"> <strong> <font face="Arial">安装 PyDev</font> </strong> </span> </a> </p> <p>首先Q从 Eclipse Web 站点上下?EclipseQ请参阅 <a ><font color="#996699">参考资?/font></a> 一节中的链接)(j)QƈҎ(gu)(zhn)的q_Q按照下面的安装指南安装 EclipseQ?</p> <p>Eclipse 的更新机制 PyDev 插g的安装更加容易。从 Eclipse 中选择 <b>Help > Software Updates > Update Manager</b>Q启?Install/Update 视角。在左下角的 Feature Updates 视图中,?PyDev 插g更新站点作ؓ(f)新的 Site Bookmark d到“Sites to Visit”文件夹下。Eclipse ?PyDev 更新站点 URL ?http://pydev.sf.net/updates/。现在,Feature Updates ~辑器中应该昄出“PyDev”这一Ҏ(gu)。在 Feature Updates ~辑器中Q展开 <b>PyDev > Other</b>Q选择其中昄?PyDev Ҏ(gu)(臛_应该?0.4.1Q。然后选择 “Install Now”安装该Ҏ(gu)。Eclipse 下?PyDev 插gQƈ其安装?Eclipse 中?</p> <p> <a name="N10085"> <span id="ljvwbrw" class="smalltitle"> <strong> <font face="Arial">导入样例目</font> </strong> </span> </a> </p> <p>问本目中用的样例代码Q可先下?zip 文gQ请参阅 <a ><font color="#996699">参考资?/font></a>一节)(j)Q在文gpȝ中展开?zip 文gQ然后将其中的项目导?Eclipse。导入项目的Ҏ(gu)是先切换?Resource 视角Q选择 <b>File > Import</b>Q再选择“Existing Project into Workspace”,然后选择(zhn)展开 zip 文g的位|。这ӞNavigator 视图中应该出?feedParserTest 目?</p> <p>样例目中已l包含了(jin) Fead Parser 通用资源解析库,该库?Python 开放源代码许可协议发布。有?Feed Parser 目 Web |站的链接,请参?<a ><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" > <b> <font color="#996699">回页?/font> </b> </a> </td> </tr> </tbody> </table> </td> </tr> </tbody> </table> <br /> <br /> <p> <a name="N1009C"> <span id="xoabgay" class="atitle"> <font face="Arial" size="4">PyDev 漫游</font> </span> </a> </p> <p>现在开始学?fn)如何通过已导入的目?jin)?PyDev 的特性。PyDev 正处于开发过E中Q但已经是非帔R效的 Python 开发环境。现在的 PyDev 主要包括以下Ҏ(gu):(x)</p> <ul> <li>包含 Python 语法高亮昄Ҏ(gu)的 Python ~辑器? </li> <li>q行 Python 语法分析Qƈ?Python ~辑器和 Tasks 视图中高亮显C错误? </li> <li>可将制表W{换成I格的选项? </li> <li>Outline 视图昄导入的库、类以及(qing)函数? </li> <li>l端视图中的 Python 堆栈跟踪信息可超链接到源代码中? </li> <li>源代码内部的链接;同一模块内的导入和函数调用可通过链接进行导航? </li> <li>?Navigator 视图中运?Python 脚本的能力? </li> <li>调试器支持断炏V代码单步执行以?qing)显C变量的倹{?</li> </ul> <p> <a name="N100C0"> <span id="gaqrlqz" class="smalltitle"> <strong> <font face="Arial">PyDev 选项H口</font> </strong> </span> </a> </p> <p>通过 <b>Window > Preferences</b>Qƈ选择 PyDevQ请参阅?1Q,便可讉K PyDev 选项。第一l选项可以改变 PyDev 在源代码中处理制表符的方式,q可以改变语法元素的颜色?</p> <br /> <a name="N100CE"> <b>?1. PyDev 选项H口</b> </a> <br /> <img alt="PyDev 选项H口" src="http://www-128.ibm.com/developerworks/cn/opensource/os-ecant/pyDevPrefs.jpg" /> <br /> <p> <a name="N100DB"> <span id="vifzlfz" class="smalltitle"> <strong> <font face="Arial">讄 Python 解释?/font> </strong> </span> </a> </p> <p>PyDev Debug 选项可以选择 Python 解释器,供执?Python 代码时用。如?PyDev 无法扑ֈ Python 解释器,或者想使用别的解释器,可在此设|(请参阅图 2Q?</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 id="zqcztjk" class="smalltitle"> <strong> <font face="Arial">处理源代?/font> </strong> </span> </a> </p> <p>我的大部?Python 工作都是?Resource 视角中完成的。用方法是先切换到 Resource 视角Q然后在左上角的 Navigator 视图中双?feedParserTest/src/feedparserTest/FeedparserTest.py 文g。Python ~辑器打开该文Ӟ?Python 语法q行解析Q完成设|颜色和语法(g)查的工作Q请参阅?3Q?</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>如果源代码中有Q何错误,则显C在右下角的 Tasks 视图中显C出来。双?Tasks 视图中的错误Q便可找到那条讨厌的代码行?</p> <p>Outline 视图在左下角Q其中用一U便于浏览的l构昄出当前正在编辑的文g。导入的库、类、函数全都显C出来,通过双击 Outline 视图中的目Q便可以实现D。PyDev 在编?Python 文g的过E中寚wq行预先解析的工作,同时更新 Outline 视图Q执行语法检查,q用不同颜色昄语法元素?</p> <p> <a name="N10111"> <span id="egdmgaf" class="smalltitle"> <strong> <font face="Arial">~辑器的Ҏ(gu)?/font> </strong> </span> </a> </p> <p>PyDev 0.4 版在 Python 源代码编辑器中ؓ(f)函数和导入库加入?jin)超链接的特性。如果在过某项导入或函数调用(必须?<code>PYTHONPATH</code> 目录中)(j)的同时按?Control 键,PyDev p昄Z个超链接Q这h可以在导入库或函数的源代码之间导航。请注意Qؓ(f)?jin)在?zhn)自q源代码中跨模块用该Ҏ(gu)(从一个模块链接到另一个模块)(j)Q必M?<code>PYTHONPATH</code> 环境变量Q在其中加入q些模块Q这?PyDev 可以找到它们了(jin)?</p> <p>Z已经开始将一些优异的源代码编辑特性加入最新版本的 PyDev 中,其中包括代码块注释与取消注释,以及(qing)代码左右UMQ请参阅?4Q?</p> <br /> <a name="N10127"> <b>?4. PyDev ~辑器的其他Ҏ(gu)?/b> </a> <br /> <img alt="PyDev ~辑器的其他Ҏ(gu)? src="http://www-128.ibm.com/developerworks/cn/opensource/os-ecant/editorFeatures.jpg" /> <br /> <p> <a name="N10134"> <span id="oxfnhxn" class="smalltitle"> <strong> <font face="Arial">q行 Python 脚本</font> </strong> </span> </a> </p> <p>如果不能执行代码Q那?IDE 也不是太有用。ؓ(f)执行 Python 代码Q可?Navigator 视图中选择 feedparser.py 文gQ用右键点击Q然后选择 <b>Python > Run</b>。随后会(x)昄 Python 的启动配|窗口(请参阅图 5Q?</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 启动配置H口中可以定义脚本执行的当前目录Q传递给脚本的参敎ͼ以及(qing)用哪一?Python 解释器运行脚本。feedparser.py 以一?RSS URL 作ؓ(f)参数Q所以可在参数字D中填入 URLQ如 http://www.ibm.com/developerworks/news/dw_dwtp.rss。其余的~省定义可以了(jin)Q所以单?<b>Run</b>?</p> <p>脚本执行时输Z息显C在 Console H口中。如果有错误出现QConsole H口中将昄堆栈跟踪信息Q其中的每一行都可以通过链接找?Python 源代码?</p> <p> <a name="N10158"> <span id="ktfydxv" class="smalltitle"> <strong> <font face="Arial">Python 调试?/font> </strong> </span> </a> </p> <p>Python 调试器是最q才加入 PyDev 插g中的。要使用调试器,可在 Python ~辑器中想中断的代码行的左侧点击Q设|断炏V在?6 中,我在 feedparser.py ?1830 行处讄?jin)断炏V然后在 Navigator 视图中选择q个 Python 模块Q点d键,选择“Python > Debug...”。这时将昄与前面相似的一个启动配|窗口。点?<b>Debug</b> q入 Debug 视角Q同时启动调试器?</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 视图昄当前正在执行的进E和U程Q右上角?Variables 视图昄当前q行域中的所有变量,Python ~辑器会(x)昄调试器目前停在哪条语句上Q同时所有的输出信息都显CZ Console 视图中。调试器可以通过 Debug 视图底部的按钮或 Run 菜单q行控制?</p> <p> <a name="N10176"> <span id="omuvsbg" class="smalltitle"> <strong> <font face="Arial">其他 Eclipse Ҏ(gu)?/font> </strong> </span> </a> </p> <p>Eclipse ?qing)其插gq具备很多其他的Ҏ(gu),可应用于 Python 开发中Q如 XML ~辑器、UML ~辑器(不过大多数是?Java 代码Z?j)?j)Q还有资源控制方面的插g。目?Eclipse 插g站点上列出的插g几乎?500 个(请参?<a ><font color="#996699">参考资?/font></a> 一节中的相关链接)(j)。我着重介l一个对很多 Python 开发h员都特别有用的插Ӟ(x)Eclipse 发行版中已经包括?CVS 插gQ不q不?x)讨论细节内宏V?</p> <p>Eclipse 中包括特性丰富的集成 CVSQ?/p> <ul> <li>支持 SSH、pserver、ext {连接方法? </li> <li>基本 CVS 命o(h)的支持:(x)(g)出项目、提交变更、更新、向.cvsignore 中增加文件或模式{等? </li> <li>文g合ƈ查看? </li> <li>在源代码控制中实现对文g不同之处的比较? </li> <li>目同步Qƈ用资料库昄出删除和新增的内宏V?</li> </ul> <p>q可以通过提供其他插g来支持其他源代码控制pȝQ如 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" > <b> <font color="#996699">回页?/font> </b> </a> </td> </tr> </tbody> </table> </td> </tr> </tbody> </table> <br /> <br /> <p> <a name="N1019B"> <span id="xztnsmr" class="atitle"> <font face="Arial" size="4">?Eclipse 中?Python 的交互式 shell</font> </span> </a> </p> <p>Python 解释器支?Python 代码的交互式执行。这U方式对于调试一D代码是非常有用的,因ؓ(f)不用把代码放q?Python 脚本中ƈ执行脚本?jin)。同ӞPython 解释器的交互模式可以很容易地集成?Eclipse 中?</p> <p>要增加对 Python 交互式执行的支持Q可通过 <b>Run > External Tools > External Tools</b> 增加一?External Tool 启动E序。这时将打开 External Tool 启动E序配置H口。在 Configurations 列表中选择“Program”,然后点击“New”创Z个新的配|。将该配|命名ؓ(f)诸如 "pythonInteractive" 之类Q然后设|?LocationQo(h)其指向?zhn)?Python 解释器,接着Q将 "-i" 作ؓ(f)唯一的参C递进来(请参阅图 7Q?</p> <p>?Common 选项卡下Q选中复选框Q该配|在 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 > External Tools > pythonInterpreter</b>。Python 解释器的输出昄?Console 视图中。Console 中可输入 Python 命o(h)q执行,像从命令行中执?Python 一栗ؓ(f)导入q在交互模式下用模块,(zhn)需要将模块的位|增加到 <code>PYTHONPATH</code> 环境变量中?</p> <p>?Eclipse Console 中执?Python 与用命o(h)行执行的不同之处在于Q无法启用命令历史特性(通过向上和向下的方向键实玎ͼ(j)Q因?Eclipse Console ?x)自p释这些键?</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" > <b> <font color="#996699">回页?/font> </b> </a> </td> </tr> </tbody> </table> </td> </tr> </tbody> </table> <br /> <br /> <p> <a name="N101C9"> <span id="hyrstch" class="atitle"> <font face="Arial" size="4">?Python 开发中使用 Ant</font> </span> </a> </p> <p>Python ?x)在它需要的时候自动编译模块。这意味着 Python 开发h员通常不必昑ּ地对模块q行~辑。即便如此,有时候手工编?Python 代码q是很有用的Q同Ӟ构徏和部|过E中q有很多其他斚w的内容可以自动化实现。这也正是构建工L(fng)用武之地?</p> <p>我将着重介l来?Java ~程世界中的 Apache AntQ这个工具可大量应用?Python 开发中。Apache Ant ?Java ~程领域内事实上的标准构建工兗它更加MQ与 Java 技术结合得更好Q可用于替代其他的构建工兗Ant 可以在支?Java ~程语言的Q何一U^Cq行。尽我们需要的大多数构建特?Ant 都已l提供了(jin)Q但如果要将 Ant 用做 Python 构徏工具Q还是需要有一些关键的?Python 相关的特性。我已经开发了(jin)若干定制?Ant 插gQ用 Ant 的行话讲叫做 taskQ,可提供构?Python 旉要的特定?Python 的特性?</p> <p>Ant ?XML 作ؓ(f)描述构徏的格式。build 文gl织为需要执行的目标。每一个目标都可能依赖于其他的目标。Ant 根据?zhn)所h执行的目标,以及(qing)一l依赖目标,来执行Q何需要的目标。每一个目标都可能包含L数量?Ant dQ而由 Ant d实际执行目标的工作。Ant 有很多内|的dQ可以完成诸如编?Java 代码、生成文档、操U|件和目录Q同时第三方又提供了(jin)很多附加的Q务?</p> <p> <a name="N101D8"> <span id="cliqrhb" class="smalltitle"> <strong> <font face="Arial">安装 Python Ant ?/font> </strong> </span> </a> </p> <p>我将通过?feedparser 目创徏构徏脚本来介l?Ant 构徏脚本?Python Ant d的基知识。ؓ(f)?jin)?Python Ant dQ?zhn)需要下载ƈ安装包含q些d?Java 库。首先,?<a ><font color="#996699">参考资?/font></a> 一节中列出?URL 中下?Python Ant d库(pyAntTasks.jarQ。然后,?JAR 文g拯?Eclipse ?Ant 插g下的 lib 目录中。这应该?Eclipse 安装目录下Ş?plugins/org.apache.ant_1.5.3 的子目录?</p> <p>Python Ant d库拷贝完毕之后,必须?Eclipse 中启用库。选择 <b>Window > Preferences</b>Q然后选择 <b>Ant > Runtime</b>。将 Ant Home Entries 展开Q其中可看到 Eclipse 使用的库QJAR 文gQ列表。选择?Add JAR”,然后?Eclipse Ant 插g?lib 目录中选择 Python Ant JAR 文gQ就可以刚刚拷贝的 Python Ant JAR 文g加入库列表中Q请参阅?8Q?</p> <br /> <a name="N101F0"> <b>?8. ?classpath 中加?Python Ant d</b> </a> <br /> <img alt="?classpath 中加?Python Ant d" src="http://www-128.ibm.com/developerworks/cn/opensource/os-ecant/addPyAntTasks.jpg" /> <br /> <p>(zhn)现在应该能够创建和q行包含 Python d?Ant 构徏脚本?jin)。下面进入构本内部! </p> <p> <a name="N10200"> <span id="ntqvlyw" class="smalltitle"> <strong> <font face="Arial">创徏构徏脚本</font> </strong> </span> </a> </p> <p>我将逐步介绍如何创徏一个简单的 Python 构徏脚本Q请参阅清单 1Q。完整的构徏脚本 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"><project name="feedParserTest" default="compile"> <taskdef resource="pyAntTasks.properties"/> <property name="src.dir" value="src"/> <target name="compile"> <py-compile dir="${src.dir}" pythonpath="${src.dir}" optimize="0"/> </target> </project> </font> </code> </pre> </td> </tr> </tbody> </table> <br /> <p>先介l一个只~译 Python 样例代码的构本?lt;project> 标签L构徏脚本的根标签?lt;taskdef> 标签声明在整个构本中使用?Python d。在构徏脚本的底部,可以定义 <code>compile</code> 目标。目标元素内部是 <code>compile</code> q行期间执行的Q务。特别的?py-compile dQ它负责?src 目录开始,~译所有的 Python 代码。该d?x)递归遍历所有的子目录,q编译所有的 Python 模块。脚本中没有采用?src 目录编码到调用之处的方式,而是在构本中定义?jin)称?src.dir 的属性。然后,在需要用这个目录名的时候,可以通过 <code>${src.dir}</code> 来引用?</p> <p>要运行构本,可从 Eclipse 中打开它。Eclipse h内置?Ant 构徏脚本~辑和浏览功能。Outline 视图可以昄出构本的l构。在 Navigator 视图中,选择该构本,用右键点击,然后选择“Run Ant...”。选择 <code>compile</code> 目标Q然后点几ZRun”。构本执行过E中的输Z息应该显C在 Console 视图中,表示q行成功?</p> <p> <a name="N10229"> <span id="qhebrwu" class="smalltitle"> <strong> <font face="Arial">Python 脚本执行d</font> </strong> </span> </a> </p> <p>接下来将向构本中加入新的目标Q用于执?Python 脚本Q请参阅清单 2Q。在本例中,可以?RSS URL 作ؓ(f)参数来执?feedparser.py 脚本?</p> <br /> <a name="N10232"> <b>清单 2. q行 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"> <target name="run.feedparser" depends="compile"> <py-run script="src/feedparser/feedparser.py" pythonpath="${src.dir}" optimize="0"> <arg value="http://www.ibm.com/developerworks/news/dw_dwtp.rss"> </py-run> </target> </font> </code> </pre> </td> </tr> </tbody> </table> <br /> <p>上面的目标以 RSS URL 为唯一的参数来执行 feedparser.py 脚本。该目标声明Z赖于 <code>compile</code> 目标Q所以后者将首先执行。实际上q一步ƈ不是很必要,因ؓ(f) Python ?x)根据需要自动编译源代码。如果?zhn)执?<code>run.feedparser</code> 目标Q就?x)运?feedparser.py 脚本Q同时将 RSS 的内容输出到 Console 中?</p> <p> <a name="N10247"> <span id="xhpqvtr" class="smalltitle"> <strong> <font face="Arial">Python 文d</font> </strong> </span> </a> </p> <p>Python ?API 文~制机制?Java 技术中?JavaDoc pȝcMQ称?PyDoc。在构徏脚本中加入清?3 中列出的如下 XML 片断Q可为所有的 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: <property name="pydoc.dir" value="pydoc"/> 2: 3: <target name="init"> 4: <mkdir dir="${pydoc.dir}"/> 5: </target> 6: 7: <target name="pydoc" depends="init,compile"> 8: <py-doc pythonpath="${src.dir}" destdir="${pydoc.dir}"> 9: <fileset dir="${src.dir}"> 10: <include name="**/*"/> 11: </fileset> 12: </py-doc> 13: </target> </font> </code> </pre> </td> </tr> </tbody> </table> <br /> <p> <code>从对上述 pydoc 目标的解析可看出Q第 7 行声明了(jin)目标名称Qƈ指出它依赖于 <code>init</code> ?<code>compile</code> 目标。这意味着在运?pydoc 目标之前QAnt 必须保证 <code>init</code> ?<code>compile</code> 目标已经q行Q如果没有,则首先运行这两个目标?</code> </p> <p> <code>pydoc</code> 目标所依赖?<code>init</code> 目标在第 3 至第 5 行定义?<code>init</code> 目标仅仅创徏?jin)一个存?PyDoc API 文文g的目录。如前所qͼ要ؓ(f)所生成文的保存位|定义一个属性,名ؓ(f) pydoc.dir?</p> <p>W?8 行开始是 py-doc d。如前所qͼ(zhn)传入生?pydoc q程中所使用?<code>PYTHONPATH</code> ?<code>destdir</code> 属性告?py-doc d生成的 HTML 文档输出C处?</p> <p>W?9 至第 11 行定义了(jin)在生成文档的q程中应该处理哪?Python 源文件。文仉?Ant 脚本中通用的结构,可用于定义所操作的一l文件。这是一U很强大的特性,它(zhn)能够通过名字模式、布?yu)(dng)逻辑和文件属性来选择所要操作的文g。Ant 文中有q方面的完整描述。本例中递归选择?jin)“src”目录下的所有文件?</p> <p> <a name="N1028D"> <span id="nifglfz" class="smalltitle"> <strong> <font face="Arial">Python 单元试d</font> </strong> </span> </a> </p> <p>Python 中具有标准的单元试框架Q从 Python 2.3 开始。在 Python 2.2 中这只是可选模块)(j)Q与 Java jUnit 框架十分cM。测试用例的l构?jUnit 采用相同的方式。每一个待试的类和模块通常都具有自q试cR测试类中包含测试装|(fixtureQ,它们?<code>setUp</code> 函数中初始化。每一个测试都~写为测试类中的一个独立的试函数。unittest 框架?x)在试函数之间循环往复,先调?<code>setUp</code> 、再试函数、然后清除( <code>tearDown</code> Q测试函数。请参阅清单 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)> 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 模块基本试功能的测试类。完整的试c见 feedParserTest 目下的 src/feedparserTest/FeedparserTest.py?<code>setUp</code> 函数负责准备整个试q程中需要用的试装置Q在本例中只有测试用?RSS 文g的目录,试函数对其进行解析?<code>testParse09Rss</code> 是真正的试函数。这个函数调?feedparser.parse 函数Q传递测试用?RSS 文gQ输?gu)析结果,q过 TestCase cȝ assert 函数执行基本的检查统作。如果Q?assert 的求值结果不是真Q或是在执行q程中抛ZQ何异常,unittest ׃(x)报告一ơ测试失败或错误。最后的两行负责在这个测试类内部q行试Q方法是直接q行该模块即可?</p> <p>要独立运行该试c,可以按前面所说的相同方式q行 FeedparserTest.py 模块。在 Eclipse Navigator 视图中选择 FeedparserTest.pyQ然后通过 <b>Python > Run</b> q行。此时显C启动配|窗口。除 Base 目录之外Q其他都保持~省值即可。Base 目录必须?feedParserTest 目的目录,q样才能在当前目录下扑ֈ RSS 文gQtestData/developerworks.rssQ。修?base 目录的设|,然后点击“Run”。输Z息显C在 Console 上?</p> <p>(zhn)也许希望我们编写的所有单元测试都能够作ؓ(f)构徏的一部分自动执行。将下面清单 5 所C的构徏片断加入构徏脚本便可实现?</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: <target name="tests" depends="compile"> 2: <py-test pythonpath="${src.dir}" dir="."> 3: <fileset dir="${src.dir}"> 4: <include name="**/*Test.py"/> 5: </fileset> 6: </py-test> 7: </target> </font> </code> </pre> </td> </tr> </tbody> </table> <br /> <p>W一行是目标声明Q这与其他的脚本相同。第 2 至第 6 行调?py-test d。这部分代码在“src”目录下查找所有以“Test.py”结所有文Ӟq运行所有测试?<code>PYTHONPATH</code> 讄为“src”,试执行的当前工作目录就是当前目录(?’)(j)?</p> <p>q行目标的方法是先运行构本,再选择执行“tests”目标。该目标运行所有以“Test.py”结试用例Q本例中仅有 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" > <b> <font face="Verdana" color="#996699">回页?/font> </b> </a> </td> </tr> </tbody> </table> </td> </tr> </tbody> </table> <br /> <br /> <p> <a name="N102D4"> <span id="kbcsiga" class="atitle"> <font face="Arial" size="4">l束?/font> </span> </a> </p> <p>Eclipse ?PyDev 插g的结合,以及(qing) Apache Ant ?Python Ant d一起用,可以?Python 开发提供完全集成的开发环境和构徏/部v工具。这些工具尚在开发过E中Q因此要l常查看是否有更斎ͼ如果(zhn)觉得特别希望看到某U特性,可以卯v袖管自力更生?</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" > <b> <font face="Verdana" color="#996699">回页?/font> </b> </a> </td> </tr> </tbody> </table> </td> </tr> </tbody> </table> <br /> <br /> <p> <a name="resources"> <span id="befczwf" class="atitle"> <font face="Arial" size="4">参考资?</font> </span> </a> </p> <ul> <li>(zhn)可以参阅本文在 developerWorks 全球站点上的 <a ><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">样例E序与源代码</font></a>?<br /><br /></li> <li>讉K <a ><font color="#996699">Eclipse Web 站点</font></a>获取 Eclipse 下蝲文g?Eclipse 文档?<br /><br /></li> <li> <a > <font color="#5c81a7">Eclipse Plug-ins Web 站点</font> </a>中包含数以百计的商业和开放源代码插gQ可供在 Eclipse 中安装?<br /><br /></li> <li> <a > <font color="#5c81a7">Apache Ant Web 站点</font> </a>上有 Ant 下蝲和有?Ant 的文档?<br /><br /></li> <li>要获?Python 的下载和相关信息Q请参阅 <a ><font color="#5c81a7">Python Web 站点</font></a>?<br /><br /></li> <li> <a > <font color="#5c81a7">PyDev SourceForge 目站点</font> </a>提供?jin)下载、文档和用户论坛?<br /><br /></li> <li> <a > <font color="#5c81a7">Python Ant tasks Web 站点</font> </a>包含最新版本的 Python Ant d?<br /><br /></li> <li>Feed Parser 是用 Python 实现的通用资源解析器,可从 <a ><font color="#5c81a7">Feed Parser Web 站点</font></a>上找到?<br /><br /></li> <li> <a > <font color="#5c81a7"> <i>Python in a Nutshell</i> </font> </a>QO'Reilly & AssociatesQ?003Q,作?Alex MartelliQ是优秀?Python 语言参考手册?<br /><br /></li> <li>?<i>developerWorks</i>?<a ><font color="#5c81a7">开放源代码目专区</font></a>中可以找到更?<a ><font color="#5c81a7">?Eclipse 用户撰写的文?/font></a>。也可以参看 <i>alphaWorks</i>上最新的 <a ><font color="#5c81a7">Eclipse 技术下?/font></a>?<br /><br /></li> <li>?Developer Bookstore 的开放源代码ZQ可以找到数百本 <a ><font color="#5c81a7">开放源代码打折书籍</font></a>Q其中包括几?<a ><font color="#5c81a7">Eclipse</font></a>?<a ><font color="#5c81a7">Struts 应用E序开?/font></a> 斚w的图书?<br /><br /></li> <li>通过 <a target="new"><font color="#5c81a7">developerWorks Subscription</font></a>用最新的 IBM 工具和中间g开发及(qing)试(zhn)的应用E序Q?zhn)可以获得包括Z Eclipse ?WebSphere、DB2、Lotus、Rational、Tivoli 在内?IBM 软gQ同时还有可使用 12 个月的Y件许可,省钱出(zhn)的惌?<br /><br /></li> <li>下蝲 developerWorks Subscription _N品的免费试用版,q些产品可运行于 Linux 上,包括 WebSphere Studio Site Developer、WebSphere SDK for Web services、WebSphere Application Server、DB2 Universal Database Personal Developers Edition、Tivoli Access Manager 以及(qing) Lotus Domino Server。下载链接在 developerWorks ?<a ><font color="#5c81a7">Speed-start your Linux app</font></a>区。想更快开始么Q请自己讉K产品使用文和技术支持?<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" > <b> <font face="Verdana" color="#996699">回页?/font> </b> </a> </td> </tr> </tbody> </table> </td> </tr> </tbody> </table> <br /> <br /> <p> <a name="author"> <span id="avhtjde" 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 的创始h。这是一家Y件开发与软gN公司Q总部位于芝加哥地区。Ron Smith 为客h供基?J2EE 的企业应用程序发斚w的咨询,同时也在 RPS Technologies 内部开发Y件品。可以通过 <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.shnenglu.com/Jeff-Chen/aggbug/5521.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.shnenglu.com/Jeff-Chen/" target="_blank">Jeff-Chen</a> 2006-04-14 11:34 <a href="http://www.shnenglu.com/Jeff-Chen/archive/2006/04/14/5521.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item><item><title>Python 学习(fn)之\Q四Q?/title><link>http://www.shnenglu.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.shnenglu.com/Jeff-Chen/archive/2006/04/13/5494.html</guid><wfw:comment>http://www.shnenglu.com/Jeff-Chen/comments/5494.html</wfw:comment><comments>http://www.shnenglu.com/Jeff-Chen/archive/2006/04/13/5494.html#Feedback</comments><slash:comments>0</slash:comments><wfw:commentRss>http://www.shnenglu.com/Jeff-Chen/comments/commentRss/5494.html</wfw:commentRss><trackback:ping>http://www.shnenglu.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 OneQabout sequences and lists<br /></strong> <br />序列是不可变列表。一旦创Z(jin)一个序列就不能以Q何方式改变它?/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 />>>> </tt> <span id="bpxnhbv" 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>>>> </tt> <span id="niuoxrl" class="userinput">t</span> <br /> <span id="ojrktns" class="computeroutput">('a', 'b', 'mpilgrim', 'z', 'example')</span> <br /> <tt>>>> </tt> <span id="sydpbga" 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 id="uwtnhmg" class="computeroutput">'a'</span> <br /> <tt>>>> </tt> <span id="zjzlxrw" 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 id="vfvtywf" class="computeroutput">'example'</span> <br /> <tt>>>> </tt> <span id="hfvhirw" 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 id="srdtyhq" class="computeroutput">('b', 'mpilgrim')</span> </font> </font> </p> <table summary="Callout list" border="0"> <tbody> <tr> <td valign="top" align="left" width="12"> <a > <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">序列的定义同列表的定义方式相同,除了(jin)整个元素集是用小括号包围的而不是方括号?/font> </td> </tr> <tr> <td valign="top" align="left" width="12"> <a > <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">序列的元素象列表一h定义的次序进行排序。序列的索引象列表一样从0开始,所以一个非I序列的W一个元素L<tt> t[0]</tt>?/font> </td> </tr> <tr> <td valign="top" align="left" width="12"> <a > <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">负数索引象列表一样从序列N开始计数?/font> </td> </tr> <tr> <td valign="top" align="left" width="12"> <a > <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">分片也可以用,p列表一栗注意当分割一个列表时Q会(x)得到一个新的列表;当分割一个序列时Q会(x)得到一个新的序列?/font> </td> </tr> </tbody> </table> <p> <a name="odbchelper.tuplemethods"> </a> <b> <font face="Arial" size="2">?1.22. 序列没有Ҏ(gu)</font> <br /></b> <font face="Arial"> <font size="2"> <br /> <tt>>>> </tt> <span id="mkhtudb" class="userinput">t</span> <br /> <span id="mhtuktn" class="computeroutput">('a', 'b', 'mpilgrim', 'z', 'example')</span> <br /> <tt>>>> </tt> <span id="zxnoauz" class="userinput">t.append(<tt class="string">"new"</tt>)</span> </font> <br /></font> <font face="Arial"> <font size="2"> <span id="blfyven" class="traceback">Traceback (innermost last):<br />File "<interactive input>", line 1, in ?<br />AttributeError: 'tuple' object has no attribute 'append'</span> <br /> <tt>>>> </tt> <span id="oughtna" 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 id="mgsicwq" class="traceback">Traceback (innermost last):<br />File "<interactive input>", line 1, in ?<br />AttributeError: 'tuple' object has no attribute 'remove'</span><br /><tt>>>> </tt><span id="tvdexcw" class="userinput">t.index(<tt class="string">"example"</tt>)</span>  <br /></font></font><font face="Arial"><font size="2"><span id="tgwtjhi" class="traceback">Traceback (innermost last):<br />  File "<interactive input>", line 1, in ?<br />AttributeError: 'tuple' object has no attribute 'index'</span><br /><tt>>>></tt><span id="htyhqva" class="userinput"><tt class="string">"z"</tt> <tt class="keyword">in</tt> t</span>  <br /></font></font><font face="Arial"><font size="2"><span id="fdxgoey" class="computeroutput">1</span>   </font></font></p> <table summary="Callout list" border="0"> <tbody> <tr> <td valign="top" align="left" width="12"> <a > <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> Ҏ(gu)?/font> </td> </tr> <tr> <td valign="top" align="left" width="12"> <a > <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> Ҏ(gu)?/font> </td> </tr> <tr> <td valign="top" align="left" width="12"> <a > <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> Ҏ(gu)?/font> </td> </tr> <tr> <td valign="top" align="left" width="12"> <a > <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">那么序列有什么好处呢Q?/font> </p> <ul> <li> <font face="Arial" size="2"> <font color="#ff0000">序列比列表操作速度快。如果你定义?jin)一个值集合常量,q且唯一要用它做的是不断地遍历它Q用序列代替列表?/font> </font> </li> <li> <font face="Arial" size="2">记得我说q?/font> <a title="Example 1.11. Mixing datatypes in a dictionary" > <font face="Arial" size="2">字典关键?/font> </a> <font face="Arial" size="2">可以是整敎ͼ字符串和“几U其它的cd”吗Q序列就是那些类型之一。序列可以在字典中被用作关键字,但是列表不行?sup>[<a name="c40ab4c10b6b1ab5">2</a>]</sup></font> </li> <li> <font face="Arial" size="2">序列用在字符串格式化Q这一Ҏ(gu)们会(x)很快看到?</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>>>> </tt> <span id="prhtjsx" class="userinput">li = [1, 9, 8, 4]</span><br /><tt>>>> </tt> <span id="tklmglu" 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 id="grspmga" class="computeroutput">[2, 18, 16, 8]</span><br /><tt>>>> </tt> <span id="dqcstnd" 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 id="syotjoi" 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 > <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">Z(jin)对这一Ҏ(gu)一个感性认识,从右向左看它?<tt>li</tt> 是一个将要映的列表。Python循环遍历 <tt>li</tt> 一ơ一个元素,临时每个元素的Dl变?<tt>elem</tt>。然后Python使用函数 <tt><tt>elem</tt>*2</tt> Q接着结果追加到q回列表中?/font> </p> </td> </tr> <tr> <td valign="top" align="left" width="12"> <a > <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支持一U有的语法Q它允许你快速定义单行的最函数。这些叫?<tt>lambda</tt> 的函数是从Lisp中借用来的Q可以被用在M需要函数的地方?/font> </p> <p> <font face="Arial" size="2">Z历史的原因,<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>>>> </tt> <span id="bzlfktg" 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 id="kefgwfv" class="userinput"> <tt class="keyword">return</tt> x*2</span> <br /> <tt>...     </tt> <span id="ntfrhfv" class="userinput"> </span> <br /> <tt>>>> </tt> <span id="pnoinwq" class="userinput">f(3)</span> <br /> <span id="iheukxg" class="computeroutput">6</span> <br /> <tt>>>> </tt> <span id="qrwxvpn" 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>>>> </tt> <span id="snkpyhb" class="userinput">g(3)</span> <br /> <span id="wfglbvt" class="computeroutput">6</span> <br /> <tt>>>> </tt> <span id="qhajztu" 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 id="tvlmrwx" class="computeroutput">6</span> </font> </font> </p> <table summary="Callout list" border="0"> <tbody> <tr> <td valign="top" align="left" width="12"> <a > <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">q是一个通常的函数声明,管以前你可能没有看到过定义在交互式H口中的函数。这?... 说明它是一个多行的交互语句。只要在W一行的后面敲入回RQPython IDE?x)让你接着输入命o(h)?/font> </p> </td> </tr> <tr> <td valign="top" align="left" width="12"> <a > <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">q是一?<tt>lambda</tt> 函数Q它完成同上面普通函数相同的事情。注意这里的短的语法Q没有小括号Q?<tt>return</tt> 是默认的Qƈ且函数没有名字,只有它赋值给变量的变量名?/font> </p> </td> </tr> <tr> <td valign="top" align="left" width="12"> <a > <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> 函数赋值给一个变量而用它。这不是举世无双的东西,它只是展CZ(jin) lambda 函数只是一个内联函数?/font> </p> </td> </tr> </tbody> </table> <p> <font face="Arial" size="2">MQ?<tt>lambda</tt> 函数是一个可以接收Q意多个参?包括</font> <a title="2.3. Optional and named arguments" > <font face="Arial" size="2">可选参?/font> </a> <font face="Arial" size="2">)q且q回单个表达式值的函数?<tt>lambda</tt> 函数不能包含命o(h)Q它们所包含的表辑ּ不能过一个。不要试囑֐ <tt>lambda</tt> 函数中塞入太多的东西Q如果你需要更复杂的东西,应该定义一个普通函敎ͼ然后惌它多长就多长?/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> 函数是风格问题。不一定非要用它们,M能够使用它们的地方,都可以定义一个分ȝ普通的函数Q用它来替换。我它们用在需要封装特D的Q非重用的代码上Q用许多的一行函C?x)弄乱我的代码?/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">Zq里有几件事情需要注意。首先,我们使用?</font> <a title="2.7. The and-or trick" > <tt> <font face="Arial" size="2">and-or</font> </tt> </a> <font face="Arial" size="2">技巧的单Ş式,没问题,因ؓ(f)一?<tt>lambda</tt> 函数</font> <a title="Note: What's true in Python?" > <font face="Arial" size="2">在一个布?yu)(dng)环境?/font> </a> <font face="Arial" size="2">Mؓ(f)真?qƈ不意味着 <tt>lambda</tt> 函数不能q回假倹{函数本wL为真Q它的返回值可以ؓ(f)M倹{?</font> </p> <p> <font face="Arial" size="2">W二Q我们用了(jin) <tt>split</tt> 函数没带参数。你已经看到q它?/font> <a title="Example 1.34. Splitting a string" > <font face="Arial" size="2">1个或2个参?/font> </a> <font face="Arial" size="2">的用,但是不带参数它按I白q行分割?/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>>>></tt><span id="durwmvp" 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>>>></tt><span id="zemvhus" class="userinput"><tt class="keyword">print</tt> s</span></font>  <br /><font face="Arial"><font size="2"> <span id="afrdpyo" class="computeroutput">this   is<br />a test</span><br /><tt>>>></tt><span id="augwtch" 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 id="ardxcwq" class="computeroutput">['this', 'is', 'a', 'test']</span><br /><tt>>>></tt><span id="gmyzlcw" 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 id="xstnsmc" 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 > <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">q是一个多行字W串Q通过转义字符的定义代替了(jin)</font> <a title="Example 1.4. Defining the buildConnectionString function's doc string" > <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 > <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> 不带参数按空白进行分剌Ӏ所以三个空|一个回车,和一个制表符都是一L(fng)?/font> </font> </p> </td> </tr> <tr> <td valign="top" align="left" width="12"> <a > <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">你可以将I白l一化,通过分割一个字W串Q然后用单个I格作ؓ(f)分隔W将光新接h。这是 <tt>help</tt> 函数所做的Q将多行文档字符串合q成单行?/font> </p> </td> </tr> </tbody> </table> <p> <font face="Arial" size="2">那么 <tt>help</tt> 函数到底用这?<tt>lambda</tt> 函数Q?<tt>split</tt> 函数Q和 <tt>and-or</tt> 技巧做?jin)什么呢Q?</font> </p> <p> <a name="apihelper.funcassign"> </a> <b> <font face="Arial" size="2">?2.23. 函数赋l一个变?/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> 为真Q?<tt><tt>processFunc</tt>(<i>string</i>)</tt> 压~空白;否则Q?tt><tt>processFunc</tt>(<i>string</i>)</tt> 返回未改变的参数?</font> </font> </p> <p> <font face="Arial" size="2">在一个不很徏壮的语言实现它,象VBQ你可能创Z个函敎ͼ它接收一个字W串和一?<i><tt>collapse</tt></i> 参数Q用一?<tt>if</tt> 语句来判断是否要压羃I白或不压羃Q然后返回相应的倹{这h率低Q因为函数将不得不处理每U可能性;每次你调用它Q它?yu)不得不在给Z所惌的东西之前,判断是否要压~空白。在Python中,你可以将那种判断逻辑拿到函数外面Q而定义一个裁减过?<tt>lambda</tt> 函数来给出确切的(q且唯一)你想要的。这样做更有效率Q更漂亮Qƈ且更导致那些o(h)厌的(哦,惛_那些参数头?的错误?br /></font> </p> <img src ="http://www.shnenglu.com/Jeff-Chen/aggbug/5494.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.shnenglu.com/Jeff-Chen/" target="_blank">Jeff-Chen</a> 2006-04-13 21:49 <a href="http://www.shnenglu.com/Jeff-Chen/archive/2006/04/13/5494.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item><item><title>Python 学习(fn)之\QBrief Outlook of Library:TwoQ?/title><link>http://www.shnenglu.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.shnenglu.com/Jeff-Chen/archive/2006/04/13/5484.html</guid><wfw:comment>http://www.shnenglu.com/Jeff-Chen/comments/5484.html</wfw:comment><comments>http://www.shnenglu.com/Jeff-Chen/archive/2006/04/13/5484.html#Feedback</comments><slash:comments>0</slash:comments><wfw:commentRss>http://www.shnenglu.com/Jeff-Chen/comments/commentRss/5484.html</wfw:commentRss><trackback:ping>http://www.shnenglu.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 > <font face="Tahoma"> <font size="2"> <font color="#002c99">11.1 Output Formatting</font> </font> </font> </a> </li> <li> <a > <font face="Tahoma"> <font size="2"> <font color="#002c99">11.2 Templating</font> </font> </font> </a> </li> <li> <a > <font face="Tahoma"> <font size="2"> <font color="#002c99">11.3 Working with Binary Data Record Layouts</font> </font> </font> </a> </li> <li> <a > <font face="Tahoma"> <font size="2"> <font color="#002c99">11.4 Multi-threading</font> </font> </font> </a> </li> <li> <a > <font face="Tahoma"> <font size="2"> <font color="#002c99">11.5 Logging</font> </font> </font> </a> </li> <li> <a > <font face="Tahoma"> <font size="2"> <font color="#002c99">11.6 Weak References</font> </font> </font> </a> </li> <li> <a > <font face="Tahoma"> <font size="2"> <font color="#002c99">11.7 Tools for Working with Lists</font> </font> </font> </a> </li> <li> <a > <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" > <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 id="lcdijsm" class="verbatim"> <pre> <font face="Tahoma" size="2"> >>> import repr >>> 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" > <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 id="tvlfkxn" class="verbatim"> <pre> <font face="Tahoma" size="2"> >>> import pprint >>> t = [[[['black', 'cyan'], 'white', ['green', 'red']], [['magenta', ... 'yellow'], 'blue']]] ... >>> 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" > <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 id="dbnzpyh" class="verbatim"> <pre> <font face="Tahoma" size="2"> >>> import textwrap >>> 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.""" ... >>> 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" > <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 id="rtjzluv" class="verbatim"> <pre> <font face="Tahoma" size="2"> >>> import locale >>> locale.setlocale(locale.LC_ALL, 'English_United States.1252') 'English_United States.1252' >>> conv = locale.localeconv() # get a mapping of conventions >>> x = 1234567.8 >>> locale.format("%d", x, grouping=True) '1,234,567' >>> 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" > <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 id="vnzpfdt" class="verbatim"> <pre> <font face="Tahoma" size="2"> >>> from string import Template >>> t = Template('${village}folk send $$10 to $cause.') >>> 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 id="egpbcsb" class="verbatim"> <pre> <font face="Tahoma" size="2"> >>> t = Template('Return the $item to $owner.') >>> d = dict(item='unladen swallow') >>> t.substitute(d) Traceback (most recent call last): . . . KeyError: 'owner' >>> 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 id="nwtnvam" class="verbatim"> <pre> <font face="Tahoma" size="2"> >>> import time, os.path >>> photofiles = ['img_1074.jpg', 'img_1076.jpg', 'img_1077.jpg'] >>> class BatchRename(Template): ... delimiter = '%' >>> fmt = raw_input('Enter rename style (%d-date %n-seqnum %f-format): ') Enter rename style (%d-date %n-seqnum %f-format): Ashley_%n%f >>> t = BatchRename(fmt) >>> date = time.strftime('%d%b%y') >>> for i, filename in enumerate(photofiles): ... base, ext = os.path.splitext(filename) ... newname = t.substitute(d=date, n=i, f=ext) ... print '%s --> %s' % (filename, newname) img_1074.jpg --> Ashley_0.jpg img_1076.jpg --> Ashley_1.jpg img_1077.jpg --> 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" > <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 id="gebndxj" 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" > <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 id="mdlxnhm" 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" > <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" > <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 id="lnzlbke" 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 id="ivwxrlf" 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" > <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 id="tghmnlu" class="verbatim"> <pre> <font face="Tahoma" size="2"> >>> import weakref, gc >>> class A: ... def __init__(self, value): ... self.value = value ... def __repr__(self): ... return str(self.value) ... >>> a = A(10) # create a reference >>> d = weakref.WeakValueDictionary() >>> d['primary'] = a # does not create a reference >>> d['primary'] # fetch the object if it is still alive 10 >>> del a # remove the one reference >>> gc.collect() # run garbage collection right away 0 >>> d['primary'] # entry was automatically removed Traceback (most recent call last): File "<pyshell#108>", 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" > <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 id="bdiyoir" class="verbatim"> <pre> <font face="Tahoma" size="2"> >>> from array import array >>> a = array('H', [4000, 10, 700, 22222]) >>> sum(a) 26932 >>> a[1:3] array('H', [10, 700]) </font> </pre> </div> <p> <font face="Tahoma" size="2">The </font> <a class="ulink" > <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 id="upbnzej" class="verbatim"> <pre> <font face="Tahoma" size="2"> >>> from collections import deque >>> d = deque(["task1", "task2", "task3"]) >>> d.append("task4") >>> 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" > <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 id="ktfrdxg" class="verbatim"> <pre> <font face="Tahoma" size="2"> >>> import bisect >>> scores = [(100, 'perl'), (200, 'tcl'), (400, 'lua'), (500, 'python')] >>> bisect.insort(scores, (300, 'ruby')) >>> 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" > <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 id="kfjopuz" class="verbatim"> <pre> <font face="Tahoma" size="2"> >>> from heapq import heapify, heappop, heappush >>> data = [1, 3, 5, 7, 9, 2, 4, 6, 8, 0] >>> heapify(data) # rearrange the list into heap order >>> heappush(data, -5) # add a new entry >>> [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" > <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 id="hgwxnwy" class="verbatim"> <pre> <font face="Tahoma" size="2"> >>> from decimal import * >>> Decimal('0.70') * Decimal('1.05') Decimal("0.7350") >>> .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 id="ntbvpnh" class="verbatim"> <pre> <font face="Tahoma" size="2"> >>> Decimal('1.00') % Decimal('.10') Decimal("0.00") >>> 1.00 % 0.10 0.09999999999999995 >>> sum([Decimal('0.1')]*10) == Decimal('1.0') True >>> 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 id="tgoamgp" class="verbatim"> <pre> <font face="Tahoma" size="2"> >>> getcontext().prec = 36 >>> Decimal(1) / Decimal(7) Decimal("0.142857142857142857142857142857142857") </font> </pre> </div> <img src ="http://www.shnenglu.com/Jeff-Chen/aggbug/5484.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.shnenglu.com/Jeff-Chen/" target="_blank">Jeff-Chen</a> 2006-04-13 19:45 <a href="http://www.shnenglu.com/Jeff-Chen/archive/2006/04/13/5484.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item><item><title>Python 学习(fn)之\QBrief Outlook of Library:OneQ?/title><link>http://www.shnenglu.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.shnenglu.com/Jeff-Chen/archive/2006/04/13/5483.html</guid><wfw:comment>http://www.shnenglu.com/Jeff-Chen/comments/5483.html</wfw:comment><comments>http://www.shnenglu.com/Jeff-Chen/archive/2006/04/13/5483.html#Feedback</comments><slash:comments>0</slash:comments><wfw:commentRss>http://www.shnenglu.com/Jeff-Chen/comments/commentRss/5483.html</wfw:commentRss><trackback:ping>http://www.shnenglu.com/Jeff-Chen/services/trackbacks/5483.html</trackback:ping><description><![CDATA[ <a name="CHILD_LINKS"> <strong>Subsections</strong> </a> <ul class="ChildLinks"> <li> <a >10.1 Operating System Interface</a> </li> <li> <a >10.2 File Wildcards</a> </li> <li> <a >10.3 Command Line Arguments</a> </li> <li> <a >10.4 Error Output Redirection and Program Termination</a> </li> <li> <a >10.5 String Pattern Matching</a> </li> <li> <a >10.6 Mathematics</a> </li> <li> <a >10.7 Internet Access</a> </li> <li> <a >10.8 Dates and Times</a> </li> <li> <a >10.9 Data Compression</a> </li> <li> <a >10.10 Performance Measurement</a> </li> <li> <a >10.11 Quality Control</a> </li> <li> <a >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" ><tt class="module">os</tt></a> module provides dozens of functions for interacting with the operating system: </p> <p> </p> <div id="cifvlfv" class="verbatim"> <pre>>>> import os >>> os.system('time 0:02') 0 >>> os.getcwd() # Return the current working directory 'C:\\Python24' >>> 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 id="drstnwq" class="verbatim"> <pre>>>> import os >>> dir(os) <returns a list of all module functions> >>> help(os) <returns an extensive manual page created from the module's docstrings> </pre> </div> <p>For daily file and directory management tasks, the <a class="ulink" ><tt class="module">shutil</tt></a> module provides a higher level interface that is easier to use: </p> <p> </p> <div id="jwmvhuz" class="verbatim"> <pre>>>> import shutil >>> shutil.copyfile('data.db', 'archive.db') >>> 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" ><tt class="module">glob</tt></a> module provides a function for making file lists from directory wildcard searches: </p> <p> </p> <div id="lyobgpj" class="verbatim"> <pre>>>> import glob >>> 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" ><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 id="xoefgeu" class="verbatim"> <pre>>>> import sys >>> print sys.argv ['demo.py', 'one', 'two', 'three'] </pre> </div> <p>The <a class="ulink" ><tt class="module">getopt</tt></a> module processes <var>sys.argv</var> using the conventions of the <span id="ctuzayd" class="Unix">Unix</span><tt class="function">getopt()</tt> function. More powerful and flexible command line processing is provided by the <a class="ulink" ><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" ><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 id="fhechuk" class="verbatim"> <pre>>>> 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" ><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 id="riyoivl" class="verbatim"> <pre>>>> import re >>> re.findall(r'\bf[a-z]*', 'which foot or hand fell fastest') ['foot', 'fell', 'fastest'] >>> 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 id="ispyzey" class="verbatim"> <pre>>>> '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" ><tt class="module">math</tt></a> module gives access to the underlying C library functions for floating point math: </p> <p> </p> <div id="cejrhbo" class="verbatim"> <pre>>>> import math >>> math.cos(math.pi / 4.0) 0.70710678118654757 >>> math.log(1024, 2) 10.0 </pre> </div> <p>The <a class="ulink" ><tt class="module">random</tt></a> module provides tools for making random selections: </p> <p> </p> <div id="bhicdic" class="verbatim"> <pre>>>> import random >>> random.choice(['apple', 'pear', 'banana']) 'apple' >>> random.sample(xrange(100), 10) # sampling without replacement [30, 83, 16, 4, 8, 81, 41, 50, 18, 33] >>> random.random() # random float 0.17970987693706186 >>> 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" ><tt class="module">urllib2</tt></a> for retrieving data from urls and <a class="ulink" ><tt class="module">smtplib</tt></a> for sending mail: </p> <p> </p> <div id="iwiyoic" class="verbatim"> <pre>>>> import urllib2 >>> 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 <BR>Nov. 25, 09:43:32 PM EST >>> import smtplib >>> server = smtplib.SMTP('localhost') >>> server.sendmail('soothsayer@example.org', 'jcaesar@example.org', """To: jcaesar@example.org From: soothsayer@example.org Beware the Ides of March. """) >>> 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" ><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 id="tlicdiv" class="verbatim"> <pre># dates are easily constructed and formatted >>> from datetime import date >>> now = date.today() >>> now datetime.date(2003, 12, 2) >>> 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 >>> birthday = date(1964, 7, 31) >>> age = now - birthday >>> 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" ><tt class="module">zlib</tt></a>, <a class="ulink" ><tt class="module">gzip</tt></a>, <a class="ulink" ><tt class="module">bz2</tt></a>, <a class="ulink" ><tt class="module">zipfile</tt></a>, and <a class="ulink" ><tt class="module">tarfile</tt></a>. </p> <p> </p> <div id="pvwmvec" class="verbatim"> <pre>>>> import zlib >>> s = 'witch which has which witches wrist watch' >>> len(s) 41 >>> t = zlib.compress(s) >>> len(t) 37 >>> zlib.decompress(t) 'witch which has which witches wrist watch' >>> 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" ><tt class="module">timeit</tt></a> module quickly demonstrates a modest performance advantage: </p> <p> </p> <div id="ttndiva" class="verbatim"> <pre>>>> from timeit import Timer >>> Timer('t=a; a=b; b=t', 'a=1; b=2').timeit() 0.57535828626024577 >>> 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" ><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" ><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 id="hvhtnhq" class="verbatim"> <pre>def average(values): """Computes the arithmetic mean of a list of numbers. >>> 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" ><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 id="nyotfsm" 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" ><tt class="module">xmlrpclib</tt></a> and <a class="ulink" ><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" ><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" ><tt class="module">xml.dom</tt></a> and <a class="ulink" ><tt class="module">xml.sax</tt></a> packages provide robust support for parsing this popular data interchange format. Likewise, the <a class="ulink" ><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" ><tt class="module">gettext</tt></a>, <a class="ulink" ><tt class="module">locale</tt></a>, and the <a class="ulink" ><tt class="module">codecs</tt></a> package. </li> </ul> <img src ="http://www.shnenglu.com/Jeff-Chen/aggbug/5483.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.shnenglu.com/Jeff-Chen/" target="_blank">Jeff-Chen</a> 2006-04-13 19:43 <a href="http://www.shnenglu.com/Jeff-Chen/archive/2006/04/13/5483.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item><item><title>Python学习(fn)之\Q三Q?/title><link>http://www.shnenglu.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.shnenglu.com/Jeff-Chen/archive/2006/04/13/5444.html</guid><wfw:comment>http://www.shnenglu.com/Jeff-Chen/comments/5444.html</wfw:comment><comments>http://www.shnenglu.com/Jeff-Chen/archive/2006/04/13/5444.html#Feedback</comments><slash:comments>0</slash:comments><wfw:commentRss>http://www.shnenglu.com/Jeff-Chen/comments/commentRss/5444.html</wfw:commentRss><trackback:ping>http://www.shnenglu.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">>>> stack = [3, 4, 5]<br />>>> stack.append(6)<br />>>> stack.append(7)<br />>>> stack<br />[3, 4, 5, 6, 7]<br />>>> stack.pop()<br />7<br />>>> stack<br />[3, 4, 5, 6]<br />>>> stack.pop()<br />6<br />>>> stack.pop()<br />5<br />>>> 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">>>> queue = ["Eric", "John", "Michael"]<br />>>> queue.append("Terry")           # Terry arrives<br />>>> queue.append("Graham")          # Graham arrives<br />>>> queue.pop(0)<br />'Eric'<br />>>> queue.pop(0)<br />'John'<br />>>> 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">>>> empty = ()<br />>>> singleton = 'hello',    # <-- note trailing comma<br />>>> len(empty)<br />0<br />>>> len(singleton)<br />1<br />>>> singleton<br />('hello',)<br /><br /><br />but if you write a statement like this : <br />>>> singleton = 'hello'          # it means that you define or construct a string type,not a tuples<br />>>> singleton<br />'hello'<br />  </font> <br /> <br /> </font> </font> </font> </p> <img src ="http://www.shnenglu.com/Jeff-Chen/aggbug/5444.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.shnenglu.com/Jeff-Chen/" target="_blank">Jeff-Chen</a> 2006-04-13 11:26 <a href="http://www.shnenglu.com/Jeff-Chen/archive/2006/04/13/5444.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item><item><title>Python学习(fn)之\Q二Q?/title><link>http://www.shnenglu.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.shnenglu.com/Jeff-Chen/archive/2006/04/13/5441.html</guid><wfw:comment>http://www.shnenglu.com/Jeff-Chen/comments/5441.html</wfw:comment><comments>http://www.shnenglu.com/Jeff-Chen/archive/2006/04/13/5441.html#Feedback</comments><slash:comments>0</slash:comments><wfw:commentRss>http://www.shnenglu.com/Jeff-Chen/comments/commentRss/5441.html</wfw:commentRss><trackback:ping>http://www.shnenglu.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 OneQabout 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 />>>> # Replace some items:<br />... a[0:2] = [1, 12]<br />>>> a<br />[1, 12, 123, 1234]<br />>>> # Remove some:<br />... a[0:2] = []<br />>>> a<br />[123, 1234]<br />>>> # Insert some:<br />... a[1:1] = ['bletch', 'xyzzy']<br />>>> a<br />[123, 'bletch', 'xyzzy', 1234]<br />>>> a[:0] = a     # Insert (a copy of) itself at the beginning<br />>>> 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">>>> q = [2, 3]<br />>>> p = [1, q, 4]<br />>>> len(p)<br />3<br />>>> p[1]<br />[2, 3]<br />>>> p[1][0]<br />2<br />>>> p[1].append('xtra')    <br />>>> p<br />[1, [2, 3, 'xtra'], 4]<br />>>> 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>>>> for x in a[:]: # make a slice copy of the entire list<br />...       if len(x) > 6: <br />...           a.insert(0, x)<br />... <br />>>> 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">>>> for x in a :  # make a slice copy of the entire list<br />...       if len(x) > 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 id="psendxr" 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 id="yvhmcsb" 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" ><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 id="urhtuhb" 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 id="qchqvlu" 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 id="xvwmvau" 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.shnenglu.com/Jeff-Chen/aggbug/5441.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.shnenglu.com/Jeff-Chen/" target="_blank">Jeff-Chen</a> 2006-04-13 10:50 <a href="http://www.shnenglu.com/Jeff-Chen/archive/2006/04/13/5441.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item><item><title>Python 学习(fn)之\Q一Q?/title><link>http://www.shnenglu.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.shnenglu.com/Jeff-Chen/archive/2006/04/12/5413.html</guid><wfw:comment>http://www.shnenglu.com/Jeff-Chen/comments/5413.html</wfw:comment><comments>http://www.shnenglu.com/Jeff-Chen/archive/2006/04/12/5413.html#Feedback</comments><slash:comments>0</slash:comments><wfw:commentRss>http://www.shnenglu.com/Jeff-Chen/comments/commentRss/5413.html</wfw:commentRss><trackback:ping>http://www.shnenglu.com/Jeff-Chen/services/trackbacks/5413.html</trackback:ping><description><![CDATA[ <strong> <font face="Arial" size="2">PythonMW记( 2006-4-12 )Q?/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><></code> and <code>!=</code> are alternate spellings of the same operator. <code>!=</code> is the preferred spelling; <code><></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 <= k < 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 >= 0 <var></var> and i <= x < 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 />>>> tax = 12.5 / 100<br />>>> price = 100.50<br />>>> price * tax<br />12.5625<br />>>> price + _<br />113.0625<br />>>> round(_, 2)<br />113.06<br />>>><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.shnenglu.com/Jeff-Chen/aggbug/5413.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.shnenglu.com/Jeff-Chen/" target="_blank">Jeff-Chen</a> 2006-04-12 19:00 <a href="http://www.shnenglu.com/Jeff-Chen/archive/2006/04/12/5413.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item><item><title>初识 python!http://www.shnenglu.com/Jeff-Chen/archive/2006/04/12/5411.htmlJeff-ChenJeff-ChenWed, 12 Apr 2006 10:14:00 GMThttp://www.shnenglu.com/Jeff-Chen/archive/2006/04/12/5411.htmlhttp://www.shnenglu.com/Jeff-Chen/comments/5411.htmlhttp://www.shnenglu.com/Jeff-Chen/archive/2006/04/12/5411.html#Feedback2http://www.shnenglu.com/Jeff-Chen/comments/commentRss/5411.htmlhttp://www.shnenglu.com/Jeff-Chen/services/trackbacks/5411.html 与pythonW一ơ亲密接?
在网上搜集了(jin)很多资料和浏览了(jin)python的很多相x章,它给我的M感觉是在文本处理上的高效和语a?人性化",
面D个例子来说明我ؓ(f)什么觉?人性化":

1. Reason One :  长整型无长度限制Q除?jin)?sh)脑硬件的限制
Although both lower case "l" and upper case "L" are allowed as suffix for long integers, it is strongly recommended to always use "L", since the letter "l" looks too much like the digit "1".
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.
There is no limit for long integer literals apart from what can be stored in available memory. Some examples of plain integer literals (first row) and long integer literals (second and third rows):       
7      2147483647                                      0177
3L    79228162514264337593543950336L    0377L   0x100000000L
       79228162514264337593543950336                 0xdeadbeef


2. Reason Two : (quote) 一个pythontipQ交换两个变量的|而且不用第三个变量Q?
>>> a,b = 1,2
>>> a,b = b,a
>>> a,b
(2, 1)
>>> 

3.Reason Three:
它是用C语言开发的Q但是效率比起C语言也差?jin)多,当然没C快啦Q但是他里面的很多函数非常方便,功能比C强大很多?br />4.Reason Four : 
最让h兴奋的原因就是BitComet是它开发出来的?br />
他避免了(jin)很多初学E序设计时常常出现的问题Q尽对于大多数人来说都是几乎不?x)发生的Q但是从q点可以看出它对它的用户是傻瓜开始的。因为傻瓜才?x)犯哪些错误Q?br />
  




Jeff-Chen 2006-04-12 18:14 发表评论
]]>
þþþƷר| þˬˬƬAV鷳| þۺϾɫۺϾ99| þ˽˹Ʒ| þҹۺϾþ| þþݾþþ| ٸ88þĻ| ŷƷƵһþþþƷ | þþƷav鶹ͼƬ| 91鶹Ʒ91þþþþ| ޾ƷþþӰԺӰƬ| Ʒ˾þþþþþ| ھƷþþþӰԺձ| þþŷղAV| þþþƷSmվ| Ʒþþ| þþһƷ99þþƷ66 | ŷҹƷþþþþ˳| þþƷ۲ӰԺ| 97þù޾Ʒ| ɫۺϾþʮ·| þþƷþý| ˺ݺۺ88ۺϾþ| þþƷһ| 94þù׾Ʒ| þþþþһ| þ޾ƷĻ| ۺϾþĻӰ| 99þѹƷػ| ˺ݺۺϾþ| һþöAV| һƷ˾þ| ŷþþþþ| ݺɫþþۺƵպ| þѾDzݲƷ| þþŷղAV | þþƷŷƬ| ҹþþþþ| þ޾Ʒ˳ۺ| ƷѾþþþþþ| ƷþþƷ|