解釋器的行編輯功能并不很復(fù)雜。裝在Unix上的解釋器可能會(huì)有GNU readline 庫(kù)支持,這樣就可以額外得到精巧的交互編輯和歷史記錄功能?赡軝z查命令行編輯器支持能力最方便的方式是在主提示符下輸入Ctrl+P。如果有嘟嘟聲(計(jì)算機(jī)揚(yáng)聲器),說(shuō)明你可以使用命令行編輯功能,從附錄 A 可以查到快捷鍵的介紹。如果什么也沒(méi)有發(fā)聲,或者P顯示了出來(lái),說(shuō)明命令行編輯功能不可用,你只有用退格鍵刪掉輸入的命令了。
python
Python 2.3 (#1, Jul 30 2003, 23:22:59)
[GCC 3.2 20020927 (prerelease)] on cygwin
Type "help", "copyright", "credits" or "license" for more information.
>;>;>;
輸入多行結(jié)構(gòu)時(shí)需要從屬提示符了,例如,下面這個(gè) if 語(yǔ)句:
>;>;>; the_world_is_flat = 1
>;>;>; if the_world_is_flat:
... print "Be careful not to fall off!"
...
Be careful not to fall off!
>;>;>; 2+2
4
>;>;>; # This is a comment
... 2+2
4
>;>;>; 2+2 # and a comment on the same line as code
4
>;>;>; (50-5*6)/4
5
>;>;>; # Integer division returns the floor:
... 7/3
2
>;>;>; 7/-3
-3
像c一樣,等號(hào)(“=”)用于給變量賦值。被分配的值是只讀的。
>;>;>; x = y = z = 0 # Zero x, y and z
>;>;>; x
0
>;>;>; y
0
>;>;>; z
0
Python完全支持浮點(diǎn)數(shù),不同類型的操作數(shù)混在一起時(shí),操作符會(huì)把整型轉(zhuǎn)化為浮點(diǎn)數(shù)。
>;>;>; 'spam eggs'
'spam eggs'
>;>;>; 'doesn\'t'
"doesn't"
>;>;>; "doesn't"
"doesn't"
>;>;>; '"Yes," he said.'
'"Yes," he said.'
>;>;>; "\"Yes,\" he said."
'"Yes," he said.'
>;>;>; '"Isn\'t," she said.'
'"Isn\'t," she said.'
字符串可以通過(guò)幾種方式分行?梢栽谛屑臃葱备茏鰹槔^續(xù)符,這表示下一行是當(dāng)前行的邏輯沿續(xù)。
hello = "This is a rather long string containing\n\
several lines of text just as you would do in C.\n\
Note that whitespace at the beginning of the line is\
significant."
This is a rather long string containing
several lines of text just as you would do in C.
Note that whitespace at the beginning of the line is significant.
然而,如果我們創(chuàng)建一個(gè)“raw”行,\n序列就不會(huì)轉(zhuǎn)為換行,示例源碼最后的反斜杠和換行符n都會(huì)做為字符串中的數(shù)據(jù)處理。如下所示:
hello = r"This is a rather long string containing\n\
several lines of text much as you would do in C."
print hello
會(huì)打印為:
This is a rather long string containing\n\
several lines of text much as you would do in C.
或者,字符串可以用一對(duì)三重引號(hào)”””或'''來(lái)標(biāo)識(shí)。三重引號(hào)中的字符串在行尾不需要換行標(biāo)記,所有的格式都會(huì)包括在字符串中。
print """
Usage: thingy [OPTIONS]
-h Display this usage message
-H hostname Hostname to connect to
"""
produces the following output:
Usage: thingy [OPTIONS]
-h Display this usage message
-H hostname Hostname to connect to
解釋器打印出來(lái)的字符串與它們輸入的形式完全相同:內(nèi)部的引號(hào),用反斜杠標(biāo)識(shí)的引號(hào)和各種怪字符,都精確的顯示出來(lái)。如果字符串中包含單引號(hào),不包含雙引號(hào),可以用雙引號(hào)引用它,反之可以用單引號(hào)。(后面介紹的print語(yǔ)句,可以可以用來(lái)寫沒(méi)有引號(hào)和反斜杠的字符串)。
>;>;>; word = 'Help' + 'A'
>;>;>; word
'HelpA'
>;>;>; '<' + word*5 + '>;'
'<HelpAHelpAHelpAHelpAHelpA>;'
兩個(gè)字符串值之間的聯(lián)接是自動(dòng)的,上例第一行可以寫成“word = 'Help' 'A'”這種方式只對(duì)字符串值有效,任何字符串表達(dá)式都不適用這種方法。
>;>;>; import string
>;>;>; 'str' 'ing' # <- This is ok
'string'
>;>;>; string.strip('str') + 'ing' # <- This is ok
'string'
>;>;>; string.strip('str') 'ing' # <- This is invalid
File "<stdin>;", line 1, in ?
string.strip('str') 'ing'
^
SyntaxError: invalid syntax
字符串可以用下標(biāo)(索引)查詢;就像C一樣,字符串的第一個(gè)字符下標(biāo)是0。這里沒(méi)有獨(dú)立的字符類型,字符僅僅是大小為一的字符串。就像在Icon中那樣,字符串的子串可以通過(guò)切片標(biāo)志來(lái)表示:兩個(gè)由冒號(hào)隔開(kāi)的索引。
>;>;>; word[] # The first two characters
'He'
>;>;>; word[2:] # All but the first two characters
'lpA'
和C字符串不同,Python字符串不能改寫。按字符串索引賦值會(huì)產(chǎn)生錯(cuò)誤。
>;>;>; word[0] = 'x'
Traceback (most recent call last):
File "<stdin>;", line 1, in ?
TypeError: object doesn't support item assignment
>;>;>; word[] = 'Splat'
Traceback (most recent call last):
File "<stdin>;", line 1, in ?
TypeError: object doesn't support slice assignment
然而,可以通過(guò)簡(jiǎn)單有效的組合方式生成新的字符串:
>;>;>; word[-1] # The last character
'A'
>;>;>; word[-2] # The last-but-one character
'p'
>;>;>; word[-2:] # The last two characters
'pA'
>;>;>; word[:-2] # All but the last two characters
'Hel'
不過(guò)-0還是0,所以它不是從右邊計(jì)數(shù)的!
>;>;>; word[-100:]
'HelpA'
>;>;>; word[-10] # error
Traceback (most recent call last):
File "<stdin>;", line 1, in ?
IndexError: string index out of range
理解切片的最好方式是把索引視為兩個(gè)字符之間的點(diǎn),第一個(gè)字符的左邊是0,字符串中第n個(gè)字符的右邊是索引n,例如:
+---+---+---+---+---+
| H | e | l | p | A |
+---+---+---+---+---+
0 1 2 3 4 5
-5 -4 -3 -2 -1
第一行是字符串中給定的0到5各個(gè)索引的位置,第二行是對(duì)應(yīng)的負(fù)索引。從i到j(luò)的切片由這兩個(gè)標(biāo)志之間的字符組成。
>;>;>; # Fibonacci series:
... # the sum of two elements defines the next
... a, b = 0, 1
>;>;>; while b < 10:
... print b
... a, b = b, a+b
...
1
1
2
3
5
8
示例中介紹了一些新功能:
>;>;>; a = ['Mary', 'had', 'a', 'little', 'lamb']
>;>;>; for i in range(len(a)):
... print i, a
...
0 Mary
1 had
2 a
3 little
4 lamb作者: mq110 時(shí)間: 2005-05-31 16:52 標(biāo)題: Python 指南 4.4 break 和 continue 語(yǔ)句, 以及循環(huán)中的 else 子句
break語(yǔ)句和C中的類似,用于跳出最近的一級(jí)for或while循環(huán)。
>;>;>; for n in range(2, 10):
... for x in range(2, n):
... if n % x == 0:
... print n, 'equals', x, '*', n/x
... break
... else:
... # loop fell through without finding a factor
... print n, 'is a prime number'
...
2 is a prime number
3 is a prime number
4 equals 2 * 2
5 is a prime number
6 equals 2 * 3
7 is a prime number
8 equals 2 * 4
9 equals 3 * 3
>;>;>; def fib(n): # write Fibonacci series up to n
... """rint a Fibonacci series up to n."""
... a, b = 0, 1
... while b < n:
... print b,
... a, b = b, a+b
...
>;>;>; # Now call the function we just defined:
... fib(2000)
1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597
關(guān)鍵字def 引入了一個(gè)函數(shù)定義。在其后必須跟有函數(shù)名和包括形式參數(shù)的圓括號(hào)。函數(shù)體語(yǔ)句從下一行開(kāi)始,必須是縮進(jìn)的。函數(shù)體的第一行可以是一個(gè)字符串值,這個(gè)字符串是該函數(shù)的 文檔字符串,也可稱作docstring。
>;>;>; def fib2(n): # return Fibonacci series up to n
... """Return a list containing the Fibonacci series up to n."""
... result = []
... a, b = 0, 1
... while b < n:
... result.append(b) # see below
... a, b = b, a+b
... return result
...
>;>;>; f100 = fib2(100) # call it
>;>;>; f100 # write the result
[1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
和以前一樣,這個(gè)例子演示了一些新的Python功能:作者: mq110 時(shí)間: 2005-05-31 16:54 標(biāo)題: Python 指南 4.7 深入函數(shù)定義
有時(shí)需要定義參數(shù)個(gè)數(shù)可變的函數(shù)。有三個(gè)方法可以做到,我們可以組合使用它們。
def ask_ok(prompt, retries=4, complaint='Yes or no, please!'):
while True:
ok = raw_input(prompt)
if ok in ('y', 'ye', 'yes'): return 1
if ok in ('n', 'no', 'nop', 'nope'): return 0
retries = retries - 1
if retries < 0: raise IOError, 'refusenik user'
print complaint
這個(gè)函數(shù)還可以用以下的方式調(diào)用:ask_ok('Do you really want to quit?'),或者像這樣:ask_ok('OK to overwrite the file?', 2)。
def parrot(voltage, state='a stiff', action='voom', type='Norwegian Blue'):
print "-- This parrot wouldn't", action,
print "if you put", voltage, "Volts through it."
print "-- Lovely plumage, the", type
print "-- It's", state, "!"
可以用以下的任一方法調(diào)用:
parrot(1000)
parrot(action = 'VOOOOOM', voltage = 1000000)
parrot('a thousand', state = 'pushing up the daisies')
parrot('a million', 'bereft of life', 'jump')
不過(guò)以下幾種調(diào)用是無(wú)效的:
parrot() # required argument missing(缺少必要參數(shù))
parrot(voltage=5.0, 'dead') # non-keyword argument following keyword(在關(guān)鍵字后面有非關(guān)鍵字參數(shù))
parrot(110, voltage=220) # duplicate value for argument(對(duì)參數(shù)進(jìn)行了重復(fù)賦值)
parrot(actor='John Cleese') # unknown keyword(未知關(guān)鍵字)
通常,參數(shù)列表中的每一個(gè)關(guān)鍵字都必須來(lái)自于形式參數(shù),每個(gè)參數(shù)都有對(duì)應(yīng)的關(guān)鍵字。形式參數(shù)有沒(méi)有默認(rèn)值并不重要。實(shí)際參數(shù)不能一次賦多個(gè)值--形式參數(shù)不能在同一次調(diào)用中同時(shí)使用位置和關(guān)鍵字綁定值。這里有一個(gè)例子演示了在這種約束下所出現(xiàn)的失敗情況:
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
keys = keywords.keys()
keys.sort()
for kw in keys: print kw, ':', keywords[kw]
它可以像這樣調(diào)用:
cheeseshop('Limburger', "It's very runny, sir.",
"It's really very, VERY runny, sir.",
client='John Cleese',
shopkeeper='Michael Palin',
sketch='Cheese Shop Sketch')
當(dāng)然它會(huì)按如下內(nèi)容打。
-- 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
注意sort()方法在關(guān)鍵字字典內(nèi)容打印前被調(diào)用,否則的話,打印參數(shù)時(shí)的順序是未定義的。
>;>;>; def my_function():
... """Do nothing, but document it.
...
... No, really, it doesn't do anything.
... """
... pass
...
>;>;>; print my_function.__doc__
Do nothing, but document it.
No, really, it doesn't do anything.作者: mq110 時(shí)間: 2005-05-31 16:55 標(biāo)題: Python 指南 5. 數(shù)據(jù)結(jié)構(gòu)
本章節(jié)深入講述一些你已經(jīng)學(xué)習(xí)過(guò)的東西,并且還加入了新的內(nèi)容。
>;>;>; freshfruit = [' banana', ' loganberry ', 'passion fruit ']
>;>;>; [weapon.strip() for weapon in freshfruit]
['banana', 'loganberry', 'passion fruit']
>;>;>; vec = [2, 4, 6]
>;>;>; [3*x for x in vec]
[6, 12, 18]
>;>;>; [3*x for x in vec if x >; 3]
[12, 18]
>;>;>; [3*x for x in vec if x < 2]
[]
>;>;>; [[x,x**2] for x in vec]
[[2, 4], [4, 16], [6, 36]]
>;>;>; [x, x**2 for x in vec] # error - parens required for tuples
File "<stdin>;", line 1, in ?
[x, x**2 for x in vec]
^
SyntaxError: invalid syntax
>;>;>; [(x, x**2) for x in vec]
[(2, 4), (4, 16), (6, 36)]
>;>;>; vec1 = [2, 4, 6]
>;>;>; vec2 = [4, 3, -9]
>;>;>; [x*y for x in vec1 for y in vec2]
[8, 6, -18, 16, 12, -36, 24, 18, -54]
>;>;>; [x+y for x in vec1 for y in vec2]
[6, 5, -7, 8, 7, -5, 10, 9, -3]
>;>;>; [vec1*vec2 for i in range(len(vec1))]
[8, 12, -54]
為使鏈表推導(dǎo)式匹配for循環(huán)的行為,可以在推導(dǎo)之外保留循環(huán)變量:
>;>;>; x = 100 # this gets overwritten
>;>;>; [x**3 for x in range(5)]
[0, 1, 8, 27, 64]
>;>;>; x # the final value for range(5)
4
5.2 del 語(yǔ)句
有一個(gè)方法可從鏈表中刪除指定索引的元素:del語(yǔ)句。這個(gè)方法也可以從鏈表中刪除切片(之前我們是把一個(gè)空鏈表賦給切片)。例如:
>;>;>; a = [-1, 1, 66.6, 333, 333, 1234.5]
>;>;>; del a[0]
>;>;>; a
[1, 66.6, 333, 333, 1234.5]
>;>;>; del a[2]
>;>;>; a
[1, 66.6, 1234.5]
del 也可以用于刪除整個(gè)變量:
>;>;>; del a
此后再引用這個(gè)名字會(huì)發(fā)生錯(cuò)誤(至少要到給它賦另一個(gè)值為止)。后面我們還會(huì)發(fā)現(xiàn)del的其它用法。
>;>;>; knights = {'gallahad': 'the pure', 'robin': 'the brave'}
>;>;>; for k, v in knights.items():
... print k, v
...
gallahad the pure
robin the brave
在序列中循環(huán)時(shí),索引位置和對(duì)應(yīng)值可以使用 enumerate() 函數(shù)同時(shí)得到。
>;>;>; for i, v in enumerate(['tic', 'tac', 'toe']):
... print i, v
...
0 tic
1 tac
2 toe
同時(shí)循環(huán)兩個(gè)或更多的序列,可以使用 zip() 整體解讀。
>;>;>; 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.
比較操作可以通過(guò)邏輯操作符and和or組合,比較的結(jié)果可以用not來(lái)取反義。這些操作符的優(yōu)先級(jí)又低于比較操作符,在它們之中,not具有最高的優(yōu)先級(jí),or的優(yōu)先組最低,所以A and not B or C 等于 (A and (not B)) or C。當(dāng)然,表達(dá)式可以用期望的方式表示。
邏輯操作符and 和or 也稱作短路操作符:它們的參數(shù)從左向右解析,一旦結(jié)果可以確定就停止。例如,如果A和C為真而B(niǎo)為假,A and B and C 不會(huì)解析C。作用于一個(gè)普通的非邏輯值時(shí),短路操作符的返回值通常是最后一個(gè)變量。
def fib(n): # write Fibonacci series up to n
a, b = 0, 1
while b < n:
print b,
a, b = b, a+b
def fib2(n): # return Fibonacci series up to n
result = []
a, b = 0, 1
while b < n:
result.append(b)
a, b = b, a+b
return result
現(xiàn)在進(jìn)入Python解釋器用如下命令導(dǎo)入這個(gè)模塊:
>;>;>; import sys
>;>;>; sys.ps1
'>;>;>; '
>;>;>; sys.ps2
'... '
>;>;>; sys.ps1 = 'C>; '
C>; print 'Yuck!'
Yuck!
C>;
這兩個(gè)變量只在解釋器的交互模式下有意義(此處原文為:These two variables are only defined if the interpreter is in interactive mode. )。
6.4.1 從包中導(dǎo)入全部信息(Importing * From a Package)
那么當(dāng)用戶寫下from Sound.Effects import *時(shí)會(huì)發(fā)生什么事?理想中,總是希望在文件系統(tǒng)中找出包中所有的子模塊,然后導(dǎo)入它們。不幸的是,這個(gè)操作在Mac 和 Windows 平臺(tái)上工作的并不太好,這些文件系統(tǒng)的文件大小寫并不敏感!在這些平臺(tái)上沒(méi)有什么方法可以確保一個(gè)叫ECHO.PY的文件應(yīng)該導(dǎo)入為模塊echo、Echo或ECHO。(例如,Windows 95有一個(gè)討厭的習(xí)慣,它會(huì)把所有的文件名都顯示為首字母大寫的風(fēng)格。) DOS 8+3文件名限制又給長(zhǎng)文件名模塊帶來(lái)了另一個(gè)有趣的問(wèn)題。
>;>;>; s = 'Hello, world.'
>;>;>; str(s)
'Hello, world.'
>;>;>; repr(s)
"'Hello, world.'"
>;>;>; str(0.1)
'0.1'
>;>;>; repr(0.1)
'0.10000000000000001'
>;>;>; x = 10 * 3.25
>;>;>; y = 200 * 200
>;>;>; s = 'The value of x is ' + repr(x) + ', and y is ' + repr(y) + '...'
>;>;>; print s
The value of x is 32.5, and y is 40000...
>;>;>; # The repr() of a string adds string quotes and backslashes:
... hello = 'hello, world\n'
>;>;>; hellos = repr(hello)
>;>;>; print hellos
'hello, world\n'
>;>;>; # The argument to repr() may be any Python object:
... repr((x, y, ('spam', 'eggs')))
"(32.5, 40000, ('spam', 'eggs'))"
>;>;>; # reverse quotes are convenient in interactive sessions:
... `x, y, ('spam', 'eggs')`
"(32.5, 40000, ('spam', 'eggs'))"
以下兩種方法可以輸出平方和立方表:
>;>;>; import math
>;>;>; print 'The value of PI is approximately %5.3f.' % math.pi
The value of PI is approximately 3.142.
如果有超過(guò)一個(gè)的字符串要格式化為一體,就需要將它們傳入一個(gè)元組做為右值,如下所示:
>;>;>; for name, phone in table.items():
... print '%-10s ==>; %10d' % (name, phone)
...
Jack ==>; 4098
Dcab ==>; 7678
Sjoerd ==>; 4127
大多數(shù)類C的格式化操作都需要你傳入適當(dāng)?shù)念愋停贿^(guò)如果你沒(méi)有定義異常,也不會(huì)有什么從內(nèi)核中主動(dòng)的彈出來(lái)。(however, if you don't you get an exception, not a core dump)使用 %s 格式會(huì)更輕松些:如果對(duì)應(yīng)的參數(shù)不是字符串,它會(huì)通過(guò)內(nèi)置的 str() 函數(shù)轉(zhuǎn)化為字符串。Python支持用 * 作為一個(gè)隔離(整型的)參數(shù)來(lái)傳遞寬度或精度。Python不支持C的 %n 和 %p 操作符。
如果可以逐點(diǎn)引用要格式化的變量名,就可以產(chǎn)生符合真實(shí)長(zhǎng)度的格式化字符串,不會(huì)產(chǎn)生間隔。這一效果可以通過(guò)使用 form %(name)結(jié)構(gòu)來(lái)實(shí)現(xiàn):
>;>;>; f.read()
'This is the entire file.\n'
>;>;>; f.read()
''
f.readline() 從文件中讀取單獨(dú)一行,字符串結(jié)尾會(huì)自動(dòng)加上一個(gè)換行符,只有當(dāng)文件最后一行沒(méi)有以換行符結(jié)尾時(shí),這一操作才會(huì)被忽略。這樣返回值就不會(huì)有什么混淆不清,如果 if f.readline() 返回一個(gè)空字符串,那就表示到達(dá)了文件末尾,如果是一個(gè)空行,就會(huì)描述為‘\n’,一個(gè)只包含換行符的字符串。
>;>;>; f.readline()
'This is the first line of the file.\n'
>;>;>; f.readline()
'Second line of the file\n'
>;>;>; f.readline()
''
f.readlines() 返回一個(gè)列表,其中包含了文件中所有的數(shù)據(jù)行。如果給定了 sizehint 參數(shù),就會(huì)讀入多于一行的比特?cái)?shù),從中返回行列表。這個(gè)功能通常用于高效讀取大型行文件,避免了將整個(gè)文件讀入內(nèi)存。這種操作只返回完整的行。
>;>;>; f.readlines()
['This is the first line of the file.\n', 'Second line of the file\n']
f.write(string) 將 string 的內(nèi)容寫入文件,返回None。
>;>;>; f.write('This is a test\n')
f.tell() 返回一個(gè)整數(shù),代表文件對(duì)象在文件中的指針位置,該數(shù)值計(jì)量了自文件開(kāi)頭到指針處的比特?cái)?shù)。需要改變文件對(duì)象指針話話,使用“f.seek(offset, from_what)” 。指針在該操作中從指定的引用位置移動(dòng) offset 比特,引用位置由 from_what 參數(shù)指定。. from_what 值為0表示自文件起初處開(kāi)始,1表示自當(dāng)前文件指針位置開(kāi)始,2表示自文件末尾開(kāi)始。 from_what 可以乎略,其默認(rèn)值為零,此時(shí)從文件頭開(kāi)始。
>;>;>; f=open('/tmp/workfile', 'r+')
>;>;>; f.write('0123456789abcdef')
>;>;>; f.seek(5) # Go to the 6th byte in the file
>;>;>; f.read(1)
'5'
>;>;>; f.seek(-3, 2) # Go to the 3rd byte before the end
>;>;>; f.read(1)
'd'
文件使用完后,調(diào)用 f.close() 可以關(guān)閉文件,釋放打開(kāi)文件后占用的系統(tǒng)資源。調(diào)用 f.close()之后,再調(diào)用文件對(duì)象會(huì)自動(dòng)引發(fā)錯(cuò)誤。
>;>;>; f.close()
>;>;>; f.read()
Traceback (most recent call last):
File "<stdin>;", line 1, in ?
ValueError: I/O operation on closed file
文件對(duì)象還有一些不太常用的附加方法,比如 isatty() 和 truncate() 在庫(kù)參考手冊(cè)中有文件對(duì)象的完整指南。
>;>;>; 10 * (1/0)
Traceback (most recent call last):
File "<stdin>;", line 1, in ?
ZeroDivisionError: integer division or modulo by zero
>;>;>; 4 + spam*3
Traceback (most recent call last):
File "<stdin>;", line 1, in ?
NameError: name 'spam' is not defined
>;>;>; '2' + 2
Traceback (most recent call last):
File "<stdin>;", line 1, in ?
TypeError: cannot concatenate 'str' and 'int' objects
錯(cuò)誤信息的最后一行指出發(fā)生了什么錯(cuò)誤。異常也有不同的類型,異常類型做為錯(cuò)誤信息的一部分顯示出來(lái):示例中的異常分別為零除錯(cuò)誤( ZeroDivisionError ),命名錯(cuò)誤( NameError)和類型錯(cuò)誤( TypeError )。打印錯(cuò)誤信息時(shí),異常的類型作為異常的內(nèi)置名顯示。對(duì)于所有的內(nèi)置異常都是如此,不過(guò)用戶自定義異常就不一定了(盡管這是一個(gè)很有用的約定)。標(biāo)準(zhǔn)異常名是內(nèi)置的標(biāo)識(shí)(沒(méi)有保留關(guān)鍵字)。
>;>;>; while True:
... try:
... x = int(raw_input("lease enter a number: ")
... break
... except ValueError:
... print "Oops! That was no valid number. Try again..."
...
try 語(yǔ)句按如下方式工作:
class TransitionError(Error):
"""Raised when an operation attempts a state transition that's not
allowed.
Attributes:
previous -- state at beginning of transition
next -- attempted new state
message -- explanation of why the specific transition is not allowed
"""
用C++術(shù)語(yǔ)來(lái)講,所有的類成員(包括數(shù)據(jù)成員)都是公有(public)的,所有的成員函數(shù)都是虛擬(virtual)的。用Modula-3的術(shù)語(yǔ)來(lái)講,在成員方法中沒(méi)有什么簡(jiǎn)便的方式(shorthands)可以引用對(duì)象的成員:方法函數(shù)在定義時(shí)需要以引用的對(duì)象做為第一個(gè)參數(shù),以調(diào)用時(shí)則會(huì)隱式引用對(duì)象。這樣就形成了語(yǔ)義上的引入和重命名。( This provides semantics for importing and renaming. )但是,像C++而非Modula-3中那樣,大多數(shù)帶有特殊語(yǔ)法的內(nèi)置操作符(算法運(yùn)算符、下標(biāo)等)都可以針對(duì)類的需要重新定義。
Python的一個(gè)特別之處在于其賦值操作總是在最里層的作用域。賦值不會(huì)復(fù)制數(shù)據(jù)——只是將命名綁定到對(duì)象。刪除也是如此:“del x ”只是從局部作用域的命名空間中刪除命名x。事實(shí)上,所有引入新命名的操作都作用于局部作用域。特別是import語(yǔ)句和函數(shù)定將模塊名或函數(shù)綁定于局部作用域。(可以使用global語(yǔ)句將變量引入到全局作用域。)
# Function defined outside the class
def f1(self, x, y):
return min(x, x+y)
class C:
f = f1
def g(self):
return 'hello world'
h = g
現(xiàn)在 f, g 和 h 都是類C的屬性,引用的都是函數(shù)對(duì)象,因此它們都是C實(shí)例的方法--h(huán)嚴(yán)格等于g。要注意的是這種習(xí)慣通常只會(huì)迷惑程序的讀者。
class DerivedClassName(BaseClassName):
<statement-1>;
.
.
.
<statement-N>;
命名 BaseClassName (示例中的基類名)必須與派生類定義在一個(gè)作用域內(nèi)。除了類,還可以用表達(dá)式,基類定義在另一個(gè)模塊中時(shí)這一點(diǎn)非常有用:
class DerivedClassName(modname.BaseClassName):
派生類定義的執(zhí)行過(guò)程和基類是一樣的。構(gòu)造派生類對(duì)象時(shí),就記住了基類。這在解析屬性引用的時(shí)候尤其有用:如果在類中找不到請(qǐng)求調(diào)用的屬性,就搜索基類。如果基類是由別的類派生而來(lái),這個(gè)規(guī)則會(huì)遞歸的應(yīng)用上去。
john = Employee() # Create an empty employee record
# Fill the fields of the record
john.name = 'John Doe'
john.dept = 'computer lab'
john.salary = 1000
某一段Python代碼需要一個(gè)特殊的抽象數(shù)據(jù)結(jié)構(gòu)的話,通?梢詡魅胍粋(gè)類,事實(shí)上這模仿了該類的方法。例如,如果你有一個(gè)用于從文件對(duì)象中格式化數(shù)據(jù)的函數(shù),你可以定義一個(gè)帶有Read()和Readline()方法的類,以此從字符串緩沖讀取數(shù)據(jù),然后將該類的對(duì)象作為參數(shù)傳入前述的函數(shù)。
9.9 迭代器
現(xiàn)在你可能注意到大多數(shù)容器對(duì)象都可以用 for 遍歷:
for element in [1, 2, 3]:
print element
for element in (1, 2, 3):
print element
for key in {'one':1, 'two':2}:
print key
for char in "123":
print char
for line in open("myfile.txt":
print line
這種形式的訪問(wèn)清晰、簡(jiǎn)潔、方便。這種迭代器的用法在Python中普遍而且統(tǒng)一。在后臺(tái),for 語(yǔ)句在容器對(duì)象中調(diào)用 iter() 。 該函數(shù)返回一個(gè)定義了 next() 方法的迭代器對(duì)象,它在容器中逐一訪問(wèn)元素。沒(méi)有后續(xù)的元素時(shí),next() 拋出一個(gè) StopIteration 異常通知 for 語(yǔ)句循環(huán)結(jié)束。以下是其工作原理的示例:
>;>;>; s = 'abc'
>;>;>; it = iter(s)
>;>;>; it
<iterator object at 0x00A1DB50>;
>;>;>; it.next()
'a'
>;>;>; it.next()
'b'
>;>;>; it.next()
'c'
>;>;>; it.next()
除了創(chuàng)建和保存程序狀態(tài)的自動(dòng)方法,當(dāng)發(fā)生器終結(jié)時(shí),還會(huì)自動(dòng)拋出 StopIteration異常。綜上所述,這些功能使得編寫一個(gè)正則函數(shù)成為創(chuàng)建迭代器的最簡(jiǎn)單方法。作者: mq110 時(shí)間: 2005-05-31 16:58 標(biāo)題: Python 指南 10. What Now?
Reading this tutorial has probably reinforced your interest in using Python -- you should be eager to apply Python to solve your real-world problems. Now what should you do?
You should read, or at least page through, the Python Library Reference, which gives complete (though terse) reference material about types, functions, and modules that can save you a lot of time when writing Python programs. The standard Python distribution includes a lot of code in both C and Python; there are modules to read Unix mailboxes, retrieve documents via HTTP, generate random numbers, parse command-line options, write CGI programs, compress data, and a lot more; skimming through the Library Reference will give you an idea of what's available.
The major Python Web site is http://www.python.org/; it contains code, documentation, and pointers to Python-related pages around the Web. This Web site is mirrored in various places around the world, such as Europe, Japan, and Australia; a mirror may be faster than the main site, depending on your geographical location. A more informal site is http://starship.python.net/, which contains a bunch of Python-related personal home pages; many people have downloadable software there. Many more user-created Python modules can be found in a third-party repository at http://www.vex.net/parnassus.
For Python-related questions and problem reports, you can post to the newsgroup comp.lang.python, or send them to the mailing list at python-list@python.org. The newsgroup and mailing list are gatewayed, so messages posted to one will automatically be forwarded to the other. There are around 120 postings a day (with peaks up to several hundred), asking (and answering) questions, suggesting new features, and announcing new modules. Before posting, be sure to check the list of Frequently Asked Questions (also called the FAQ), at http://www.python.org/doc/FAQ.html, or look for it in the Misc/ directory of the Python source distribution. Mailing list archives are available at http://www.python.org/pipermail/. The FAQ answers many of the questions that come up again and again, and may already contain the solution for your problem.作者: mq110 時(shí)間: 2005-05-31 16:58 標(biāo)題: Python 指南 A. Interactive Input Editing and History Substitution
Some versions of the Python interpreter support editing of the current input line and history substitution, similar to facilities found in the Korn shell and the GNU Bash shell. This is implemented using the GNU Readline library, which supports Emacs-style and vi-style editing. This library has its own documentation which I won't duplicate here; however, the basics are easily explained. The interactive editing and history described here are optionally available in the Unix and CygWin versions of the interpreter.
This chapter does not document the editing facilities of Mark Hammond's PythonWin package or the Tk-based environment, IDLE, distributed with Python. The command line history recall which operates within DOS boxes on NT and some other DOS and Windows flavors is yet another beast.
A.1 Line Editing
If supported, input line editing is active whenever the interpreter prints a primary or secondary prompt. The current line can be edited using the conventional Emacs control characters. The most important of these are: C-A (Control-A) moves the cursor to the beginning of the line, C-E to the end, C-B moves it one position to the left, C-F to the right. Backspace erases the character to the left of the cursor, C-D the character to its right. C-K kills (erases) the rest of the line to the right of the cursor, C-Y yanks back the last killed string. C-underscore undoes the last change you made; it can be repeated for cumulative effect.
A.2 History Substitution
History substitution works as follows. All non-empty input lines issued are saved in a history buffer, and when a new prompt is given you are positioned on a new line at the bottom of this buffer. C-P moves one line up (back) in the history buffer, C-N moves one down. Any line in the history buffer can be edited; an asterisk appears in front of the prompt to mark a line as modified. Pressing the Return key passes the current line to the interpreter. C-R starts an incremental reverse search; C-S starts a forward search.
A.3 Key Bindings
The key bindings and some other parameters of the Readline library can be customized by placing commands in an initialization file called ~/.inputrc. Key bindings have the form
key-name: function-name
or
"string": function-name
and options can be set with
set option-name value
For example:
# I prefer vi-style editing:
set editing-mode vi
# Edit using a single line:
set horizontal-scroll-mode On
# Rebind some keys:
Meta-h: backward-kill-word
"\C-u": universal-argument
"\C-x\C-r": re-read-init-file
Note that the default binding for Tab in Python is to insert a Tab character instead of Readline's default filename completion function. If you insist, you can override this by putting
Tab: complete
in your ~/.inputrc. (Of course, this makes it harder to type indented continuation lines.)
Automatic completion of variable and module names is optionally available. To enable it in the interpreter's interactive mode, add the following to your startup file:A.1
This binds the Tab key to the completion function, so hitting the Tab key twice suggests completions; it looks at Python statement names, the current local variables, and the available module names. For dotted expressions such as string.a, it will evaluate the the expression up to the final "." and then suggest completions from the attributes of the resulting object. Note that this may execute application-defined code if an object with a __getattr__() method is part of the expression.
A more capable startup file might look like this example. Note that this deletes the names it creates once they are no longer needed; this is done since the startup file is executed in the same namespace as the interactive commands, and removing the names avoids creating side effects in the interactive environments. You may find it convenient to keep some of the imported modules, such as os, which turn out to be needed in most sessions with the interpreter.
# Add auto-completion and a stored history file of commands to your Python
# interactive interpreter. Requires Python 2.0+, readline. Autocomplete is
# bound to the Esc key by default (you can change it - see readline docs).
#
# Store the file in ~/.pystartup, and set an environment variable to point
# to it: "export PYTHONSTARTUP=/max/home/itamar/.pystartup" in bash.
#
# Note that PYTHONSTARTUP does *not* expand "~", so you have to put in the
# full path to your home directory.
import atexit
import os
import readline
import rlcompleter
if os.path.exists(historyPath):
readline.read_history_file(historyPath)
atexit.register(save_history)
del os, atexit, readline, rlcompleter, save_history, historyPath
A.4 Commentary
This facility is an enormous step forward compared to earlier versions of the interpreter; however, some wishes are left: It would be nice if the proper indentation were suggested on continuation lines (the parser knows if an indent token is required next). The completion mechanism might use the interpreter's symbol table. A command to check (or even suggest) matching parentheses, quotes, etc., would also be useful.作者: mq110 時(shí)間: 2005-05-31 16:59 標(biāo)題: Python 指南 B. Floating Point Arithmetic: Issues and Limitations
Floating-point numbers are represented in computer hardware as base 2 (binary) fractions. For example, the decimal fraction
0.125
has value 1/10 + 2/100 + 5/1000, and in the same way the binary fraction
0.001
has value 0/2 + 0/4 + 1/8. These two fractions have identical values, the only real difference being that the first is written in base 10 fractional notation, and the second in base 2.
Unfortunately, most decimal fractions cannot be represented exactly as binary fractions. A consequence is that, in general, the decimal floating-point numbers you enter are only approximated by the binary floating-point numbers actually stored in the machine.
The problem is easier to understand at first in base 10. Consider the fraction 1/3. You can approximate that as a base 10 fraction:
0.3
or, better,
0.33
or, better,
0.333
and so on. No matter how many digits you're willing to write down, the result will never be exactly 1/3, but will be an increasingly better approximation to 1/3.
In the same way, no matter how many base 2 digits you're willing to use, the decimal value 0.1 cannot be represented exactly as a base 2 fraction. In base 2, 1/10 is the infinitely repeating fraction
Stop at any finite number of bits, and you get an approximation. This is why you see things like:
>;>;>; 0.1
0.10000000000000001
On most machines today, that is what you'll see if you enter 0.1 at a Python prompt. You may not, though, because the number of bits used by the hardware to store floating-point values can vary across machines, and Python only prints a decimal approximation to the true decimal value of the binary approximation stored by the machine. On most machines, if Python were to print the true decimal value of the binary approximation stored for 0.1, it would have to display
instead! The Python prompt (implicitly) uses the builtin repr() function to obtain a string version of everything it displays. For floats, repr(float) rounds the true decimal value to 17 significant digits, giving
0.10000000000000001
repr(float) produces 17 significant digits because it turns out that's enough (on most machines) so that eval(repr(x)) == x exactly for all finite floats x, but rounding to 16 digits is not enough to make that true.
Note that this is in the very nature of binary floating-point: this is not a bug in Python, it is not a bug in your code either, and you'll see the same kind of thing in all languages that support your hardware's floating-point arithmetic (although some languages may not display the difference by default, or in all output modes).
Python's builtin str() function produces only 12 significant digits, and you may wish to use that instead. It's unusual for eval(str(x)) to reproduce x, but the output may be more pleasant to look at:
>;>;>; print str(0.1)
0.1
It's important to realize that this is, in a real sense, an illusion: the value in the machine is not exactly 1/10, you're simply rounding the display of the true machine value.
Other surprises follow from this one. For example, after seeing
>;>;>; 0.1
0.10000000000000001
you may be tempted to use the round() function to chop it back to the single digit you expect. But that makes no difference:
>;>;>; round(0.1, 1)
0.10000000000000001
The problem is that the binary floating-point value stored for "0.1" was already the best possible binary approximation to 1/10, so trying to round it again can't make it better: it was already as good as it gets.
Another consequence is that since 0.1 is not exactly 1/10, adding 0.1 to itself 10 times may not yield exactly 1.0, either:
>;>;>; sum = 0.0
>;>;>; for i in range(10):
... sum += 0.1
...
>;>;>; sum
0.99999999999999989
Binary floating-point arithmetic holds many surprises like this. The problem with "0.1" is explained in precise detail below, in the "Representation Error" section. See The Perils of Floating Point for a more complete account of other common surprises.
As that says near the end, ``there are no easy answers.'' Still, don't be unduly wary of floating-point! The errors in Python float operations are inherited from the floating-point hardware, and on most machines are on the order of no more than 1 part in 2**53 per operation. That's more than adequate for most tasks, but you do need to keep in mind that it's not decimal arithmetic, and that every float operation can suffer a new rounding error.
While pathological cases do exist, for most casual use of floating-point arithmetic you'll see the result you expect in the end if you simply round the display of your final results to the number of decimal digits you expect. str() usually suffices, and for finer control see the discussion of Pythons's % format operator: the %g, %f and %e format codes supply flexible and easy ways to round float results for display.
B.1 Representation Error
This section explains the ``0.1'' example in detail, and shows how you can perform an exact analysis of cases like this yourself. Basic familiarity with binary floating-point representation is assumed.
Representation error refers to that some (most, actually) decimal fractions cannot be represented exactly as binary (base 2) fractions. This is the chief reason why Python (or Perl, C, C++, Java, Fortran, and many others) often won't display the exact decimal number you expect:
>;>;>; 0.1
0.10000000000000001
Why is that? 1/10 is not exactly representable as a binary fraction. Almost all machines today (November 2000) use IEEE-754 floating point arithmetic, and almost all platforms map Python floats to IEEE-754 "double precision". 754 doubles contain 53 bits of precision, so on input the computer strives to convert 0.1 to the closest fraction it can of the form J/2**N where J is an integer containing exactly 53 bits. Rewriting
1 / 10 ~= J / (2**N)
as
J ~= 2**N / 10
and recalling that J has exactly 53 bits (is >;= 2**52 but < 2**53), the best value for N is 56:
That is, 56 is the only value for N that leaves J with exactly 53 bits. The best possible value for J is then that quotient rounded:
>;>;>; q, r = divmod(2L**56, 10)
>;>;>; r
6L
Since the remainder is more than half of 10, the best approximation is obtained by rounding up:
>;>;>; q+1
7205759403792794L
Therefore the best possible approximation to 1/10 in 754 double precision is that over 2**56, or
7205759403792794 / 72057594037927936
Note that since we rounded up, this is actually a little bit larger than 1/10; if we had not rounded up, the quotient would have been a little bit smaller than 1/10. But in no case can it be exactly 1/10!
So the computer never ``sees'' 1/10: what it sees is the exact fraction given above, the best 754 double approximation it can get:
>;>;>; .1 * 2L**56
7205759403792794.0
If we multiply that fraction by 10**30, we can see the (truncated) value of its 30 most significant decimal digits:
meaning that the exact number stored in the computer is approximately equal to the decimal value 0.100000000000000005551115123125. Rounding that to 17 significant digits gives the 0.10000000000000001 that Python displays (well, will display on any 754-conforming platform that does best-possible input and output conversions in its C library -- yours may not!).作者: mq110 時(shí)間: 2005-05-31 17:00 標(biāo)題: Python 指南 C. History and License
C.1 History of the software
Python was created in the early 1990s by Guido van Rossum at Stichting Mathematisch Centrum (CWI, see http://www.cwi.nl/) in the Netherlands as a successor of a language called ABC. Guido remains Python's principal author, although it includes many contributions from others.
In 1995, Guido continued his work on Python at the Corporation for National Research Initiatives (CNRI, see http://www.cnri.reston.va.us/) in Reston, Virginia where he released several versions of the software.
In May 2000, Guido and the Python core development team moved to BeOpen.com to form the BeOpen PythonLabs team. In October of the same year, the PythonLabs team moved to Digital Creations (now Zope Corporation; see http://www.zope.com/). In 2001, the Python Software Foundation (PSF, see http://www.python.org/psf/) was formed, a non-profit organization created specifically to own Python-related Intellectual Property. Zope Corporation is a sponsoring member of the PSF.
All Python releases are Open Source (see http://www.opensource.org/ for the Open Source Definition). Historically, most, but not all, Python releases have also been GPL-compatible; the table below summarizes the various releases.
Note: GPL-compatible doesn't mean that we're distributing Python under the GPL. All Python licenses, unlike the GPL, let you distribute a modified version without making your changes open source. The GPL-compatible licenses make it possible to combine Python with other software that is released under the GPL; the others don't.
Thanks to the many outside volunteers who have worked under Guido's direction to make these releases possible.
C.2 Terms and conditions for accessing or otherwise using Python
PSF LICENSE AGREEMENT FOR PYTHON 2.3
This LICENSE AGREEMENT is between the Python Software Foundation (``PSF''), and the Individual or Organization (``Licensee'') accessing and otherwise using Python 2.3 software in source or binary form and its associated documentation.
Subject to the terms and conditions of this License Agreement, PSF hereby grants Licensee a nonexclusive, royalty-free, world-wide license to reproduce, analyze, test, perform and/or display publicly, prepare derivative works, distribute, and otherwise use Python 2.3 alone or in any derivative version, provided, however, that PSF's License Agreement and PSF's notice of copyright, i.e., ``Copyright & 2001-2003 Python Software Foundation; All Rights Reserved'' are retained in Python 2.3 alone or in any derivative version prepared by Licensee.
In the event Licensee prepares a derivative work that is based on or incorporates Python 2.3 or any part thereof, and wants to make the derivative work available to others as provided herein, then Licensee hereby agrees to include in any such work a brief summary of the changes made to Python 2.3.
PSF is making Python 2.3 available to Licensee on an ``AS IS'' basis. PSF MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMITATION, PSF MAKES NO AND DISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF PYTHON 2.3 WILL NOT INFRINGE ANY THIRD PARTY RIGHTS.
PSF SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF PYTHON 2.3 FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS A RESULT OF MODIFYING, DISTRIBUTING, OR OTHERWISE USING PYTHON 2.3, OR ANY DERIVATIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF.
This License Agreement will automatically terminate upon a material breach of its terms and conditions.
Nothing in this License Agreement shall be deemed to create any relationship of agency, partnership, or joint venture between PSF and Licensee. This License Agreement does not grant permission to use PSF trademarks or trade name in a trademark sense to endorse or promote products or services of Licensee, or any third party.
By copying, installing or otherwise using Python 2.3, Licensee agrees to be bound by the terms and conditions of this License Agreement.
BEOPEN.COM LICENSE AGREEMENT FOR PYTHON 2.0
BEOPEN PYTHON OPEN SOURCE LICENSE AGREEMENT VERSION 1
This LICENSE AGREEMENT is between BeOpen.com (``BeOpen''), having an office at 160 Saratoga Avenue, Santa Clara, CA 95051, and the Individual or Organization (``Licensee'') accessing and otherwise using this software in source or binary form and its associated documentation (``the Software'').
Subject to the terms and conditions of this BeOpen Python License Agreement, BeOpen hereby grants Licensee a non-exclusive, royalty-free, world-wide license to reproduce, analyze, test, perform and/or display publicly, prepare derivative works, distribute, and otherwise use the Software alone or in any derivative version, provided, however, that the BeOpen Python License is retained in the Software, alone or in any derivative version prepared by Licensee.
BeOpen is making the Software available to Licensee on an ``AS IS'' basis. BEOPEN MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMITATION, BEOPEN MAKES NO AND DISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF THE SOFTWARE WILL NOT INFRINGE ANY THIRD PARTY RIGHTS.
BEOPEN SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF THE SOFTWARE FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THE SOFTWARE, OR ANY DERIVATIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF.
This License Agreement will automatically terminate upon a material breach of its terms and conditions.
This License Agreement shall be governed by and interpreted in all respects by the law of the State of California, excluding conflict of law provisions. Nothing in this License Agreement shall be deemed to create any relationship of agency, partnership, or joint venture between BeOpen and Licensee. This License Agreement does not grant permission to use BeOpen trademarks or trade names in a trademark sense to endorse or promote products or services of Licensee, or any third party. As an exception, the ``BeOpen Python'' logos available at http://www.pythonlabs.com/logos.html may be used according to the permissions granted on that web page.
By copying, installing or otherwise using the software, Licensee agrees to be bound by the terms and conditions of this License Agreement.
CNRI LICENSE AGREEMENT FOR PYTHON 1.6.1
This LICENSE AGREEMENT is between the Corporation for National Research Initiatives, having an office at 1895 Preston White Drive, Reston, VA 20191 (``CNRI''), and the Individual or Organization (``Licensee'') accessing and otherwise using Python 1.6.1 software in source or binary form and its associated documentation.
Subject to the terms and conditions of this License Agreement, CNRI hereby grants Licensee a nonexclusive, royalty-free, world-wide license to reproduce, analyze, test, perform and/or display publicly, prepare derivative works, distribute, and otherwise use Python 1.6.1 alone or in any derivative version, provided, however, that CNRI's License Agreement and CNRI's notice of copyright, i.e., ``Copyright & 1995-2001 Corporation for National Research Initiatives; All Rights Reserved'' are retained in Python 1.6.1 alone or in any derivative version prepared by Licensee. Alternately, in lieu of CNRI's License Agreement, Licensee may substitute the following text (omitting the quotes): ``Python 1.6.1 is made available subject to the terms and conditions in CNRI's License Agreement. This Agreement together with Python 1.6.1 may be located on the Internet using the following unique, persistent identifier (known as a handle): 1895.22/1013. This Agreement may also be obtained from a proxy server on the Internet using the following URL: http://hdl.handle.net/1895.22/1013.''
In the event Licensee prepares a derivative work that is based on or incorporates Python 1.6.1 or any part thereof, and wants to make the derivative work available to others as provided herein, then Licensee hereby agrees to include in any such work a brief summary of the changes made to Python 1.6.1.
CNRI is making Python 1.6.1 available to Licensee on an ``AS IS'' basis. CNRI MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMITATION, CNRI MAKES NO AND DISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF PYTHON 1.6.1 WILL NOT INFRINGE ANY THIRD PARTY RIGHTS.
CNRI SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF PYTHON 1.6.1 FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS A RESULT OF MODIFYING, DISTRIBUTING, OR OTHERWISE USING PYTHON 1.6.1, OR ANY DERIVATIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF.
This License Agreement will automatically terminate upon a material breach of its terms and conditions.
This License Agreement shall be governed by the federal intellectual property law of the United States, including without limitation the federal copyright law, and, to the extent such U.S. federal law does not apply, by the law of the Commonwealth of Virginia, excluding Virginia's conflict of law provisions. Notwithstanding the foregoing, with regard to derivative works based on Python 1.6.1 that incorporate non-separable material that was previously distributed under the GNU General Public License (GPL), the law of the Commonwealth of Virginia shall govern this License Agreement only as to issues arising under or with respect to Paragraphs 4, 5, and 7 of this License Agreement. Nothing in this License Agreement shall be deemed to create any relationship of agency, partnership, or joint venture between CNRI and Licensee. This License Agreement does not grant permission to use CNRI trademarks or trade name in a trademark sense to endorse or promote products or services of Licensee, or any third party.
By clicking on the ``ACCEPT'' button where indicated, or by copying, installing or otherwise using Python 1.6.1, Licensee agrees to be bound by the terms and conditions of this License Agreement.
ACCEPT
CWI LICENSE AGREEMENT FOR PYTHON 0.9.0 THROUGH 1.2
Copyright & 1991 - 1995, Stichting Mathematisch Centrum Amsterdam, The Netherlands. All rights reserved.
Permission to use, copy, modify, and distribute this software and its documentation for any purpose and without fee is hereby granted, provided that the above copyright notice appear in all copies and that both that copyright notice and this permission notice appear in supporting documentation, and that the name of Stichting Mathematisch Centrum or CWI not be used in advertising or publicity pertaining to distribution of the software without specific, written prior permission.
STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.作者: 硬紙卡片 時(shí)間: 2005-06-01 11:34 標(biāo)題: Python 指南 好帖子upup,最好說(shuō)明是那個(gè)版本的?2.3?2.4?作者: lienjun1973 時(shí)間: 2005-08-13 07:53 標(biāo)題: Python 指南 有沒(méi)有比較精當(dāng)?shù)慕坛?或能下載的單一文件作者: limodou 時(shí)間: 2005-08-14 19:00 標(biāo)題: Python 指南 不太清楚是重新翻譯還是拷貝,如果是重新翻譯已經(jīng)有人做過(guò)了。如果是拷貝給出下載鏈接更好。