Professional Documents
Culture Documents
http://www.vithon.org/tutorial/2.5/tut.html
Bi ch dn Python
Bi ch dn Python
Guido van Rossum
Python Software Foundation
Th in t: docs@python.org
Fred L. Drake, Jr., bin tp vin
do Nguyn Thnh Nam, L Hng Vit v Lng Trng c ca nhm Python
cho ngi Vit dch
Phin bn 2.5
Ngy 19, thng 09, nm 2006
1 of 1
08/31/2011 03:19 PM
Li ta
http://www.vithon.org/tutorial/2.5/node1.html
Bi ch dn Python
Li ta
Bn quyn 2001-2006 Python Software Foundation. Gi ton quyn.
Bn quyn 2000 BeOpen.com. Gi ton quyn.
Bn quyn 1995-2000 Corporation for National Research Initiatives. Gi
ton quyn.
Bn quyn 1991-1995 Stichting Mathematisch Centrum. Gi ton quyn.
Xem phn cui ca ti liu ny v ton b thng tin quyn hn v giy php.
Tm tt:
Python l mt ngn ng d hc, v mnh m. N c nhng cu trc d liu cp
cao hiu qu v hng lp trnh i tng n gin. C php tao nh v kiu
d liu ng ca Python, cng vi bn cht thng dch bin n thnh mt
ngn ng bc nht vit kch bn (scripting) v pht trin ng dng nhanh
trong nhiu lnh vc v trn hu ht mi h thng.
Trnh thng dch Python v b th vin chun y c cung cp min ph
dng ngun hoc nh phn cho mi h thng chnh t trang ch Python,
http://www.python.org/, v c th c pht tn ty thch. Trang ch cng
phn phi v lin kt nhiu m-un Python khc, cc chng trnh v cng c,
cng nh cc ti liu thm.
Trnh thng dch Python c th c m rng d dng vi nhng chc nng v
kiu d liu c vit trong C hoc C++ (hoc ngn ng no c th gi
c t C). Python cng ph hp dng lm ngn ng m rng cho cc ng
dng m ngi dng c th ci bin.
Bi ch dn ny gii thiu vi ngi c bng mt cch d hiu nhng khi
nim c bn v cc tnh nng ca ngn ng v h thng Python. tn dng
tt nht ch dn ny, bn nn c trnh thng dch Python sn sng thc tp.
Nhng bn cng khng nht thit cn n n c ti liu ny v mi v d
u ngn v d hiu c.
tm hiu thm v cc m-un v i tng chun, xem qua ti liu Tham
kho th vin Python . S tay tham kho Python cha nh ngha ngn ng
chnh quy hn. vit cc phn m rng bng C hoc C++, bn nn c M
rng v Nhng trnh thng dch Python v Tham kho API cho Python/C. V
cng c nhiu sch khc ni su hn v Python.
Bi ch dn ny khng nhm vo vic ni v mi tnh nng, hoc thm ch l
1 of 2
08/31/2011 03:24 PM
Li ta
http://www.vithon.org/tutorial/2.5/node1.html
mi tnh nng hay dng. Thay vo , n gii thiu nhiu chc nng ng lu
ca Python v em li cho bn mt cch nhn v kiu cch v hng v ca
ngn ng ny. Sau khi c xong, bn s c th c v vit cc m-un v
chng trnh Python, v bn s sn sng tm hiu tip v nhng m-un
Python khc c nhc n trong Tham kho th vin Python.
Phin bn 2.5, ti liu c cp nht ngy 19, thng 09, nm 2006.
Xem V ti liu ny... v cch ngh thay i.
2 of 2
08/31/2011 03:24 PM
Mc lc
http://www.vithon.org/tutorial/2.5/node2.html
Bi ch dn Python
Mc lc
1. Khai v
2. S dng trnh thng dch Python
2.1 Chy trnh thng dch
2.1.1 Truyn thng s
2.1.2 Ch tng tc
2.2 Trnh thng dch v mi trng ca n
2.2.1 X l li
2.2.2 Cc kch bn Python kh thi
2.2.3 Bng m m ngun
2.2.4 Tp tin khi to tng tc
3. Gii thiu s v Python
3.1 Dng Python nh l my tnh
3.1.1 S
3.1.2 Chui
3.1.3 Chui Unicode
3.1.4 Danh sch
3.2 Nhng bc u lp trnh
4. Bn thm v lung iu khin
4.1 Cu lnh if
4.2 Cu lnh for
4.3 Hm range()
4.4 Cu lnh break v continue, v v else ca vng lp
4.5 Cu lnh pass
4.6 nh ngha hm
4.7 Bn thm v nh ngha hm
4.7.1 Gi tr thng s mc nh
4.7.2 Thng s t kha
4.7.3 Danh sch thng s bt k
4.7.4 Tho danh sch thng s
4.7.5 Dng lambda
4.7.6 Chui ti liu
5. Cu trc d liu
5.1 Bn thm v danh sch
5.1.1 Dng danh sch nh ngn xp
5.1.2 Dng danh sch nh hng i
5.1.3 Cng c lp trnh hng hm
5.1.4 Gp danh sch
5.2 Cu lnh del
5.3 B v dy
5.4 Tp hp
1 of 3
08/31/2011 03:20 PM
Mc lc
http://www.vithon.org/tutorial/2.5/node2.html
5.5 T in
5.6 K thut lp
5.7 Bn thm v iu kin
5.8 So snh dy v cc kiu khc
6. M-un
6.1 Bn thm v m-un
6.1.1 ng dn tm m-un
6.1.2 Cc tp tin Python `` dch''
6.2 Cc m-un chun
6.3 Hm dir()
6.4 Gi
6.4.1 Nhp * t mt gi
6.4.2 Tham chiu ni trong gi
6.4.3 Gi trong nhiu th mc
7. Vo v ra
7.1 nh dng ra p hn
7.2 c v vit tp tin
7.2.1 Phng thc ca i tng tp tin
7.2.2 M-un pickle
8. Li v bit l
8.1 Li c php
8.2 Bit l
8.3 X l bit l
8.4 Nng bit l
8.5 Bit l t nh ngha
8.6 nh ngha cch x l
8.7 nh ngha x l c sn
9. Lp
9.1 Vi li v thut ng
9.2 Phm vi trong Python v vng tn
9.3 Ci nhn u tin v lp
9.3.1 C php nh ngha lp
9.3.2 i tng lp
9.3.3 i tng trng hp
9.3.4 i tng phng thc
9.4 Mt vi li bnh
9.5 K tha
9.5.1 a k tha
9.6 Bin ring
9.7 Nhng iu khc
9.8 Bit l cng l lp
9.9 B lp
9.10 B to
9.11 Biu thc b to
10. Gii thiu s v b th vin chun
10.1 Giao tip vi h thng
10.2 K t thay th tp tin
2 of 3
08/31/2011 03:20 PM
Mc lc
http://www.vithon.org/tutorial/2.5/node2.html
3 of 3
08/31/2011 03:20 PM
1. Khai v
http://www.vithon.org/tutorial/2.5/node3.html
Bi ch dn Python
1. Khai v
Nu bn lm vic nhiu vi my vi tnh, mt lc no bn s nhn thy bn
mun t ng ha mt s vic. V d, bn mun thc hin mt php tm kim
v thay th vi nhiu tp tin vn bn, hoc i tn v sp xp mt lot cc tp
tin nh theo mt cch phc tp. C th bn mun vit c s d liu ty bin
nho nh, hoc mt ng dng vi giao din ha c bit, hay mt tr chi
n gin.
Nu bn l mt ngi chuyn vit phn mm, bn c th lm vic vi nhiu th
vin C/C++/Java nhng bn nhn thy thng lp i lp li vic vit/bin
dch/th/bin dch l qu tn thi gian. C th bn vit mt b cc th nghim
cho cc th vin y v nhn ra rng vit m lnh th nghim l mt vic
chn ngy. Hoc c th bn vit mt chng trnh cn s dng mt ngn ng
m rng, v bn khng mun thit k, xy dng c mt ngn ng mi cho ng
dng ca mnh.
Python chnh l ngn ng lp trnh bn cn.
Bn c th vit mt kch bn UNIX hoc mt b lnh (batch le) Windows cho
cng vic kiu ny th nhng, ngn ng kch bn ch tt cho vic chuyn cc
tp tin lng vng v sa i cc d liu vn bn, n khng thch hp cho mt
ng dng vi giao din ha hoc mt tr chi. Bn cn vit mt chng
trnh bng C/C++/Java, nhng n c th tiu tn nhiu thi gian cho vic pht
trin thm ch t bn nhp u tin ca chng trnh. S dng Python n
gin hn, chy c c trn Windows, MacOS X, v cc h iu hnh UNIX ,
v n cng gip bnh hon thnh cng vic nhanh hn.
S dng Python th n gin, nhng n l mt ngn ng lp trnh thc th,
cung cp nhiu cu trc hn v h tr cc chng trnh ln hn so vi cc
ngn ng kch bn hoc b lnh Windows. Mt khc, Python cng h tr nhiu
php kim tra li hn C, v, l mt ngn ng bc-rt-cao, n c sn cc kiu d
liu cp cao, nh cc mng v cc t in linh hot. Chnh v nhiu kiu d liu
tng qut ca n Python c ng dng rng ri hn Awk hoc thm ch l
Perl trong nhiu loi cng vic khc nhau, do c nhiu vic lm bng
Python cng d dng nh lm bng cc ngn ng khc.
Python cho php bn chia nh chng trnh ca mnh ra thnh cc m-un
c th s dng li trong cc chng trnh Python khc. N c sn rt nhiu
cc m-un chun bn c th s dng lm c s cho chng trnh ca mnh
-- hoc nh cc v d bt u hc lp trnh bng Python. Mt vi m-un
trong s chng cung cp cc chc nng nh tp tin I/O (vo/ra), cc lnh gi
hm h thng, cc socket, v thm ch cc giao tip vi cc cng c giao din
ha nh Tk.
1 of 2
08/31/2011 07:36 AM
1. Khai v
http://www.vithon.org/tutorial/2.5/node3.html
Python l mt ngn ng thng dch, iu gip bn tit kim thi gian trong
qu trnh pht trin chng trnh v vic bin dch hay lin kt l khng cn
thit. B thng dch c th c dng mt cch tng tc, lm cho vic th
nghim cc tnh nng ca ngn ng tr nn d dng, vit cc chng trnh b
i, hoc th cc chc nng trong vic pht trin chng trnh t di ln. N
cng l mt my tnh cm tay tin li.
Python cho php vit cc chng trnh nh gn v d hiu. Cc chng trnh
vit bng Python thng ngn hn so vi cc chng trnh vit bng C, C++
hoc Java, v nhiu l do:
cc kiu d liu cao cp cho php bn thc hin nhanh cc thao tc phc
tp ch vi mt lnh n gin;
pht biu lnh c nhm li bng khong cch tht u dng thay v
ng m vi cc du ngoc;
khng cn khai bo bin hoc tham s trc khi s dng.
Python c tnh m rng: nu bn bit lp trnh C th rt d b sung cc hm
c sn hoc m-un vo b thng dch, cng nh vic thc hin cc thao tc
quan trng tc ti a, hoc lin kt cc chng trnh Python vi cc th
vin ch c cung cp di dng nh phn (v d nh cc th vin ha ca
mt vi nh sn xut). Mt khi bn thc s mc ni, bn c th lin kt b
thng dch Python vo trong cc ng dng vit bng C v s dng n nh mt
tnh nng m rng hoc mt ngn ng lnh cho ng dng .
Cng xin ni lun, tn ca ngn ng ny c t sau khi BBC pht chng
trnh ``Monty Python's Flying Circus'' v n khng c lin quan g vi nhng
loi b st bn thu. Nhng tham kho mang tnh tro phng ti Monty
Python trong ti liu khng ch c cho php, m cn c c v.
By gi khi tt c cc bn b kch thch v Python, bn s mun khm ph
n k hn. Cch hc mt ngn ng tt nht l hy s dng n, bi ch dn ny
mi gi bn hy va th trnh thng dch Python khi bn va c.
Trong chng tip theo, cc phng thc s dng b thng dch s c gii
thch. iu ny khng n thun l thng tin, nhng cn l c bn cho vic
th cc v d c trnh by v sau.
Phn t hc cn li s gii thiu cc tnh nng khc nhau ca ngn ng
Python v h thng thng qua cc v d, bt u vi cc biu thc n gin,
cc cu lnh v cc kiu d liu, i qua cc hm v cc m-un, v kt thc l
tip cn vi cc khi nim cao cp nh bit l v cc lp do ngi dng t nh
ngha.
Phin bn 2.5, ti liu c cp nht ngy 19, thng 09, nm 2006.
Xem V ti liu ny... v cch ngh thay i.
2 of 2
08/31/2011 07:36 AM
http://www.vithon.org/tutorial/2.5/node4.html
Bi ch dn Python
08/31/2011 07:37 AM
http://www.vithon.org/tutorial/2.5/node4.html
2.1.2 Ch tng tc
Khi cc lnh c c t mt tty, trnh thng dch c xem l ang trong ch
tng tc. Trong ch ny n nhc lnh tip theo vi du nhc chnh
(primary prompt), thng l ba du ln hn (">>> "); vi cc dng tip ni
(continuation line), n s nhc vi du nhc th (secondary prompt), mc nh
l ba du chm ("... "). B thng dch s in mt thng bo cho mng, s
hiu phin bn v thng bo bn quyn trc khi hin du nhc:
2 of 5
08/31/2011 07:37 AM
http://www.vithon.org/tutorial/2.5/node4.html
python
Python 1.5.2b2 (#1, Feb 28 1999, 00:02:06) [GCC 2.8.1] on sunos5
Copyright 1991-1995 Stichting Mathematisch Centrum, Amsterdam
>>>
2.1
nhc th s b nhng g nhp vo v tr v du nhc chnh. G k t ngt
trong khi mt lnh ang c thc thi s gy ra bit l KeyboardInterrupt ,
trng hp ny c th c x l bng cu lnh try .
08/31/2011 07:37 AM
http://www.vithon.org/tutorial/2.5/node4.html
4 of 5
08/31/2011 07:37 AM
http://www.vithon.org/tutorial/2.5/node4.html
Ghi ch
2.1
5 of 5
08/31/2011 07:37 AM
http://www.vithon.org/tutorial/2.5/node5.html
Bi ch dn Python
3.1.1 S
Trnh thng dch ng vi tr l mt my tnh n gin: bn nhp mt biu
thc v n s tr v gi tr. C php biu thc rt d hiu: cc ton t +, -, * v
/ hot ng nh trong hu ht cc ngn ng khc (v d Pascal hay C); du
ngoc trn dng gp nhm. V d:
>>>
4
>>>
...
4
>>>
4
>>>
5
>>>
1 of 12
2+2
# This is a comment
2+2
2+2
(50-5*6)/4
# Integer division returns the floor:
08/31/2011 07:38 AM
http://www.vithon.org/tutorial/2.5/node5.html
... 7/3
2
>>> 7/-3
-3
x = y = z = 0
x
# Zero x, y and z
y
z
2 of 12
08/31/2011 07:38 AM
http://www.vithon.org/tutorial/2.5/node5.html
1.5
>>> a.imag
0.5
3.1.2 Chui
Ngoi s, Python cn lm vic c vi chui, c th c biu hin theo nhiu
cch. Chng c th c kp trong du nhy n, i:
>>> 'spam eggs'
'spam eggs'
>>> 'doesn\'t'
"doesn't"
>>> "doesn't"
3 of 12
08/31/2011 07:38 AM
http://www.vithon.org/tutorial/2.5/node5.html
"doesn't"
>>> '"Yes," he said.'
'"Yes," he said.'
>>> "\"Yes,\" he said."
'"Yes," he said.'
>>> '"Isn\'t," she said.'
'"Isn\'t," she said.'
s in:
This is a rather long string containing\n\
several lines of text much as you would do in C.
xut ra:
4 of 12
08/31/2011 07:38 AM
http://www.vithon.org/tutorial/2.5/node5.html
#
+ 'ing'
<-
'ing'
# <line 1, in ?
'ing'
^
SyntaxError: invalid syntax
<-
This is ok
This is ok
This is invalid
Cc ch mc ct lt c gi tr mc nh hu dng; ch mc u tin c gi tr
mc nh l khng, ch mc th hai mc nh l kch thc ca chui ang b
ct.
5 of 12
08/31/2011 07:38 AM
>>> word[:2]
'He'
>>> word[2:]
'lpA'
http://www.vithon.org/tutorial/2.5/node5.html
Cc ch mc c th l s m, bt u m t bn phi. V d:
>>> word[-1]
'A'
>>> word[-2]
'p'
>>> word[-2:]
'pA'
>>> word[:-2]
6 of 12
http://www.vithon.org/tutorial/2.5/node5.html
'Hel'
# (since -0 equals 0)
Xem thm:
Cc kiu dy
Chui, v cc chui Unicode c nhc n trong mc k, l v d ca
cc kiu dy, v h tr cc tc v chung c h tr bi cc kiu .
Cc phng thc chui
C chui v chui Unicode h tr mt s ln cc phng thc nhm
vo chuyn i (transform) v tm kim.
7 of 12
08/31/2011 07:38 AM
http://www.vithon.org/tutorial/2.5/node5.html
Cc tc v nh dng chui
Cc tc v nh dng chui c gi khi cc chui v chui Unicode l
ton hng bn tri ca ton t % c bn n chi tit hn y.
08/31/2011 07:38 AM
http://www.vithon.org/tutorial/2.5/node5.html
>>> u"abc"
u'abc'
>>> str(u"abc")
'abc'
>>> u""
u'\xe4\xf6\xfc'
>>> str(u"")
Traceback (most recent call last):
File "<stdin>", line 1, in ?
UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-2: ordin
9 of 12
08/31/2011 07:38 AM
http://www.vithon.org/tutorial/2.5/node5.html
Khng nh chui, l nhng i tng immutable (bt bin, khng th thay i),
ta c th thay i cc phn t ca mt danh sch:
>>> a
['spam', 'eggs', 100, 1234]
>>> a[2] = a[2] + 23
>>> a
['spam', 'eggs', 123, 1234]
10 of 12
08/31/2011 07:38 AM
http://www.vithon.org/tutorial/2.5/node5.html
>>> len(a)
8
C th lng cc danh sch (to danh sch cha cc danh sch khc), v d:
>>>
>>>
>>>
3
>>>
[2,
>>>
2
>>>
>>>
[1,
>>>
[2,
q = [2, 3]
p = [1, q, 4]
len(p)
p[1]
3]
p[1][0]
p[1].append('xtra')
p
[2, 3, 'xtra'], 4]
q
3, 'xtra']
# Fibonacci series:
# the sum of two elements defines the next
a, b = 0, 1
while b < 10:
print b
a, b = b, a+b
08/31/2011 07:38 AM
http://www.vithon.org/tutorial/2.5/node5.html
12 of 12
08/31/2011 07:38 AM
http://www.vithon.org/tutorial/2.5/node6.html
Bi ch dn Python
4.1 if cu lnh
C l loi cu lnh bit n nhiu nht l cu lnh if . V d:
>>>
>>>
...
...
...
...
...
...
...
...
...
C th khng c hoc c nhiu phn elif , v phn else l khng bt buc. T kha `elif' l vit tt
ca `else if', v dng trnh tht vo qu nhiu. Dy if ... elif ... elif ... dng thay cho cu lnh
switch hay case tm thy trong cc ngn ng khc.
4.3 range() hm
Nu bn cn lp qua mt dy s, hm c sn range() tr nn tin dng. N to ra danh sch cha cc
dy s hc:
>>> range(10)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
1 of 7
08/31/2011 07:39 AM
http://www.vithon.org/tutorial/2.5/node6.html
im dng c ch nh khng bao gi l mt phn ca danh sch to ra; range(10) to danh sch 10
gi tr, l nhng ch mc hp l cho cc phn t ca mt dy c di 10. Bn cng c th to dy bt
u t mt s khc, hoc ch r mc tin khc (ngay c mc li; i khi n cn c gi l `bc',
`step'):
>>> range(5, 10)
[5, 6, 7, 8, 9]
>>> range(0, 10, 3)
[0, 3, 6, 9]
>>> range(-10, -100, -30)
[-10, -40, -70]
4.6 nh ngha hm
2 of 7
08/31/2011 07:39 AM
http://www.vithon.org/tutorial/2.5/node6.html
Chng ta c th to mt hm in ra dy Fibonacci:
>>>
...
...
...
...
...
...
>>>
...
1 1
def fib(n):
# write Fibonacci series up to n
"""Print 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)
2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597
T kha def khai bo mt nh ngha hm . N phi c theo sau bi tn hm, v mt danh sch cc
thng s chnh quy trong ngoc n. Cc cu lnh to nn thn hm bt u t dng k tip, v bt
buc phi c tht vo. Cu lnh u tin ca thn hm c th l mt chui; chui ny l chui ti
liu, hoc docstringca hm.
C nhng cng c s dng docstrings t ng sinh ti liu trc tuyn hoc in, hoc cho php
ngi dng duyt m mt cch tng tc; vic thm docstrings vo m rt c khuyn khch, cho nn
bn hy to thi quen tt cho mnh.
Vic thc thi mt hm to ra mt bng k hiu mi dng cho cc bin cc b ca hm. Chnh xc hn,
mi php gn bin trong mt hm cha gi tr vo bng k hiu cc b; v cc tham chiu bin s trc
ht tm trong bng k hiu cc b ri trong bng k hiu ton cc, v trong bng cc tn c sn. Do
, cc bin ton cc khng th c gn gi tr trc tip trong mt hm (tr khi c t trong cu
lnh global ), mc d chng c th dc tham chiu ti.
Thng s tht s ca mt lnh gi hm c to ra trong bng k hiu cc b ca hm c gi khi n
c gi; do cc thng s c truyn theo truyn theo gi tr (call by value) (m gi tr lun l mt
4.1
3 of 7
08/31/2011 07:39 AM
http://www.vithon.org/tutorial/2.5/node6.html
4.7.1 Gi tr thng s mc nh
Dng hu dng nht l ch nh mt gi tr mc nh cho mt hoc nhiu thng s. Dng ny to mt
hm c th c gi vi t thng s hn l n c nh ngha nhn. V d:
def ask_ok(prompt, retries=4, complaint='Yes or no, please!'):
while True:
ok = raw_input(prompt)
if ok in ('y', 'ye', 'yes'): return True
if ok in ('n', 'no', 'nop', 'nope'): return False
retries = retries - 1
if retries < 0: raise IOError, 'refusenik user'
print complaint
s in 5ca hm.
Cnh bo quan trng: Gi tr mc nh ch c nh gi mt ln. im ny quan trng khi mc nh
l mt gi tr kh bin nh danh sch, t in hoc cc i tng ca hu ht mi lp. V d, hm sau
gp cc thng s truyn vo n t cc li gi sau :
def f(a, L=[]):
L.append(a)
return L
print f(1)
print f(2)
print f(3)
4 of 7
08/31/2011 07:39 AM
http://www.vithon.org/tutorial/2.5/node6.html
S in ra
[1]
[1, 2]
[1, 2, 3]
#
#
#
#
Ni chung, mt danh sch thng s phi c bt k thng s v tr (positional argument) theo sau bi bt
k thng s t kha, cc t kha phi c chn t tn thng s chnh quy. Cc thng s chnh quy
khng nht thit phi c gi tr mc nh. Khng thng s no c th nhn mt gi tr nhiu hn mt ln
-- tn thng s chnh quy tng ng vi thng s v tr khng th c dng lm t kha trong cng mt
li gi. Sau y l mt v d sai v gii hn ny:
>>> def function(a):
...
pass
...
>>> function(0, a=0)
Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: function() got multiple values for keyword argument 'a'
Khi thng s chnh quy cui c dng **name , n nhn mt t in (dictionary) cha tt c cc thng s
t kha tr nhng t kha tng ng vi thng s chnh quy. im ny c th c dng chung vi mt
thng s chnh quy dng *name (bn n trong mc con sau) v nhn mt b (tuple) cha cc thng
s v tr sau danh sch thng s chnh quy. (*name bt buc phi xut hin trc **name.) V d, nu ta
nh ngha mt hm nh sau:
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()
5 of 7
08/31/2011 07:39 AM
http://www.vithon.org/tutorial/2.5/node6.html
keys.sort()
for kw in keys: print kw, ':', keywords[kw]
N c th c gi nh vy:
cheeseshop('Limburger', "It's very runny, sir.",
"It's really very, VERY runny, sir.",
client='John Cleese',
shopkeeper='Michael Palin',
sketch='Cheese Shop Sketch')
v d nhin n s in ra:
-- 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
Lu rng phng thc sort() ca danh sch cc tn thng s t kha c gi trc khi in ni dung
ca t in keywords ; nu iu ny khng c thc hin, th t cc thng s c in ra khng xc
nh.
range(3, 6)
4, 5]
args = [3, 6]
range(*args)
4, 5]
6 of 7
08/31/2011 07:39 AM
http://www.vithon.org/tutorial/2.5/node6.html
ni no cn i tng hm. C php ca chng gii hn mt biu duy nht. V ngha, chng ch l
mt cch vit gn ca mt nh ngha hm bnh thng. Ging nh cc nh ngha hm lng nhau,
dng lambda c th tham chiu cc bin t phm vi cha n:
>>>
...
...
>>>
>>>
42
>>>
43
def make_incrementor(n):
return lambda x: x + n
f = make_incrementor(42)
f(0)
f(1)
Ghi ch
... i tng).4.1
Tht ra, gi theo tham chiu i tng (call by object reference) c th l mt din gii tt hn, v
nu mt i tng kh i c truyn vo, ni gi s nhn c cc thay i do ni c gi to
ra (v d nh cc phn t c thm vo danh sch).
Phin bn 2.5, ti liu c cp nht ngy 19, thng 09, nm 2006.
Xem V ti liu ny... v cch ngh thay i.
7 of 7
08/31/2011 07:39 AM
5. Cu trc d liu
http://www.vithon.org/tutorial/2.5/node7.html
Bi ch dn Python
5. Cu trc d liu
Chng ny din gii k hn mt vi iu bn hc c, v cng ni thm v
mt s iu mi.
08/31/2011 07:39 AM
5. Cu trc d liu
http://www.vithon.org/tutorial/2.5/node7.html
reverse()
o ngc th t cc phn t trong danh sch, ngay ti ch.
Mt v d c s dng hu ht cc phng thc ca danh sch:
>>> a = [66.25, 333, 333, 1, 1234.5]
>>> print a.count(333), a.count(66.25), a.count('x')
2 1 0
>>> a.insert(2, -1)
>>> a.append(333)
>>> a
[66.25, 333, -1, 333, 1, 1234.5, 333]
>>> a.index(333)
1
>>> a.remove(333)
>>> a
[66.25, -1, 333, 1, 1234.5, 333]
>>> a.reverse()
>>> a
[333, 1234.5, 1, 333, -1, 66.25]
>>> a.sort()
>>> a
[-1, 1, 66.25, 333, 333, 1234.5]
stack = [3, 4, 5]
stack.append(6)
stack.append(7)
stack
4, 5, 6, 7]
stack.pop()
stack
4, 5, 6]
stack.pop()
stack.pop()
stack
4]
08/31/2011 07:39 AM
5. Cu trc d liu
http://www.vithon.org/tutorial/2.5/node7.html
seq = range(8)
def add(x, y): return x+y
map(add, seq, seq)
2, 4, 6, 8, 10, 12, 14]
08/31/2011 07:39 AM
5. Cu trc d liu
http://www.vithon.org/tutorial/2.5/node7.html
']
08/31/2011 07:39 AM
5. Cu trc d liu
http://www.vithon.org/tutorial/2.5/node7.html
5 of 11
08/31/2011 07:39 AM
5. Cu trc d liu
http://www.vithon.org/tutorial/2.5/node7.html
5.3 B v dy
Chng ta thy rng danh sch v chui c nhiu thuc tnh chung, nh l c
ch mc, v cc ton t ct ming. Chng l hai v d ca dy (sequence) kiu
d liu. V Python l mt ngn ng ang pht trin, cc kiu d liu dy khc c
th c thm vo. C mt kiu dy chun khc: b (tuple).
Mt tuple gm mt s cc gi tr phn cch bi du phy, v d:
>>> t = 12345, 54321, 'hello!'
>>> t[0]
12345
>>> t
(12345, 54321, 'hello!')
>>> # Tuples may be nested:
... u = t, (1, 2, 3, 4, 5)
>>> u
((12345, 54321, 'hello!'), (1, 2, 3, 4, 5))
Khi xut ra, tuple lun lun c km gia hai du ngoc nhm cho cc
tuple lng nhau c th c thng dch chnh xc; chng c th c nhp vo
vi ngoc hoc khng, mc d thng thng chng ta vn cn cc du ngoc
(nu tuple l mt phn ca mt biu thc ln hn).
Tuple c dng nhiu. V d: cp ta (x, y), bn ghi nhn vin t c s d
liu, v.v... Ging nh chui, tuple khng th b thay i: khng th gn gi tr
mi cho tng phn t ca tuple (mc d bn c th t c cng kt qu vi
ct ming v ghp dy). Cng c th to tuple cha cc i tng kh bin v d
nh danh sch.
Vn c bit l trong vic to nn tuple cha 0 hoc mt phn t: c php
ngn ng c mt vi im ring thc hin vic ny. Tuple rng c to nn
bi mt cp ngoc rng; tuple mt phn t c to bi mt gi tr theo sau bi
mt du phy (vic cho gi tr n l vo trong ngoc khng to tuple).
Xu, nhng hiu qu. V d:
>>> empty = ()
>>> singleton = 'hello',
>>> len(empty)
0
>>> len(singleton)
1
>>> singleton
('hello',)
08/31/2011 07:39 AM
5. Cu trc d liu
http://www.vithon.org/tutorial/2.5/node7.html
5.4 Tp hp
Python cng c mt kiu d liu cho tp hp (set). Mt tp hp l mt nhm
cc phn t khng lp. ng dng c bn bao gm vic kim tra hi vin v b
cc phn t trng lp. Cc i tng tp hp cng h tr cc ton t nh hp,
giao, hiu, v hiu i xng.
y l mt v d ngn:
>>> basket = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana']
>>> fruit = set(basket)
# create a set without duplicates
>>> fruit
set(['orange', 'pear', 'apple', 'banana'])
>>> 'orange' in fruit
# fast membership testing
True
>>> 'crabgrass' in fruit
False
>>> # Demonstrate set operations on unique letters from two words
...
>>> a = set('abracadabra')
>>> b = set('alacazam')
>>> a
# unique letters in a
set(['a', 'r', 'b', 'c', 'd'])
>>> a - b
# letters in a but not in b
set(['r', 'd', 'b'])
>>> a | b
# letters in either a or b
set(['a', 'c', 'r', 'd', 'b', 'm', 'z', 'l'])
>>> a & b
# letters in both a and b
set(['a', 'c'])
>>> a ^ b
# letters in a or b but not both
set(['r', 'd', 'b', 'm', 'z', 'l'])
5.5 T in
Mt kiu d liu hu dng khc c a vo Python l t in (dictionary). T
in c tm thy trong cc ngn ng khc nh ``b nh kt hp (associative
memory)'' hoc ``mng kt hp (associative array)''. Khng nh dy c chia
ch mc t mt khong s, t in c chia ch mc t cc kha, c th l bt
k kiu khng i no; chui v s lun lun c th lm kha. Tuple c th c
7 of 11
08/31/2011 07:39 AM
5. Cu trc d liu
http://www.vithon.org/tutorial/2.5/node7.html
8 of 11
08/31/2011 07:39 AM
5. Cu trc d liu
http://www.vithon.org/tutorial/2.5/node7.html
5.6 K thut lp
Khi lp qua t in, kha v gi tr tng ng c th c ly ra cng lc bng
phng thc iteritems() .
>>> knights = {'gallahad': 'the pure', 'robin': 'the brave'}
>>> for k, v in knights.iteritems():
...
print k, v
...
gallahad the pure
robin the brave
9 of 11
08/31/2011 07:39 AM
5. Cu trc d liu
http://www.vithon.org/tutorial/2.5/node7.html
9
7
5
3
1
10 of 11
08/31/2011 07:39 AM
5. Cu trc d liu
http://www.vithon.org/tutorial/2.5/node7.html
Ch thch
5.1
... v.v...
Khng nn da vo lut so snh cc i tng khc kiu v n c th b
thay i phin bn tng lai ca ngn ng.
Phin bn 2.5, ti liu c cp nht ngy 19, thng 09, nm 2006.
Xem V ti liu ny... v cch ngh thay i.
11 of 11
08/31/2011 07:39 AM
6. M-un
http://www.vithon.org/tutorial/2.5/node8.html
Bi ch dn Python
6. M-un
Nu bn thot khi trnh thng dch v chy n li, nhng g bn nh ngha
(hm v bin) u b mt. Do , nu bn mun vit mt chng trnh di hn,
th tt nht bn nn dng mt trnh son tho chun b u vo cho trnh
thng dch v chy n vi tp tin vo ny. Vic ny c gi l to kch bn
(script). Khi chng trnh ca bn tr nn di hn, bn s mun tch n ra
thnh nhiu tp tin d duy tr. Bn s mun dng mt hm thun tin m
bn vit trong nhiu chng trnh m khng cn phi chp li nh ngha
ca n vo cc chng trnh .
h tr vic ny, Python c mt cch t cc nh ngha vo mt tp tin v
dng chng trong mt kch bn hoc trong mt phin lm vic vi trnh thng
dch. Tp tin ny c gi l m-un (module); cc nh ngha t mt m-un
c th c nhp (import) vo cc m-un khc hoc vo m-un chnh (tp
hp cc bin m bn c th truy cp ti trong mt kch bn c chy cp cao
nht v trong ch my tnh).
M-un l mt tp tin cha cc nh ngha v cu lnh Python. Tn tp tin l
tn ca m-un vi ui .py c gn vo. Trong mt m-un, tn ca m-un
(l mt chui) c th c truy cp qua mt bin ton cc __name__. V d,
dng trnh son tho ca bn to mt tp tin t tn l bo.py trong th
mc hin ti vi ni dung sau:
# Fibonacci numbers module
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
By gi chy trnh thng dch Python v nhp m-un ny vi dng lnh sau:
>>> import fibo
1 of 10
08/31/2011 10:26 AM
6. M-un
http://www.vithon.org/tutorial/2.5/node8.html
6.1
2 of 10
08/31/2011 10:26 AM
6. M-un
http://www.vithon.org/tutorial/2.5/node8.html
6.1.1 ng dn tm m-un
Khi m-un tn spam c nhp vo, trnh thng dch s tm mt tp tin tn
spam.py trong th mc hin ti, ri trong danh sch cc th mc c ch nh
bi bin mi trng PYTHONPATH. Bin ny c cng c php nh l bin mi
trng PATH, cng cha mt danh sch tn cc th mc. Khi PYTHONPATH
cha c thit lp, hoc khi tp tin khng c tm thy, vic tm kim s tip
tc tm trong ng dn mc nh ty theo khi ci Python; trn UNIX, ng
dn ny thng l .:/usr/local/lib/python.
Tht ra, m-un c tm trong danh sch cc th mc ch nh bi bin
sys.path c thit lp t th mc cha kch bn ngun (hoc th mc hin
ti), PYTHONPATH v cc mc nh khi ci t. iu ny cho php cc chng
trnh Python thay i hoc thay th ng dn tm m-un. Lu rng v th
mc cha kch bn ang chy nm trong ng dn tm kim, tn ca kch bn
nht thit phi khng trng vi tn cc m-un chun, nu khng th Python s
c sc np kch bn nh l mt m-un khi m-un c nhp vo. Thng
thng iu ny s gy li. Xem mc 6.2, ``Cc m-un chun,'' bit thm
chi tit.
3 of 10
08/31/2011 10:26 AM
6. M-un
http://www.vithon.org/tutorial/2.5/node8.html
Truyn hai c -O vo trnh thng dch Python (-OO) s khin trnh bin
dch m byte thc hin nhng ti u m trong nhng trng hp him hoi
c th dn n hng hc trong chng trnh. Hin ti ch c cc chui
__doc__ c b i khi m byte, lm cho tp tin .pyo gn hn. V mt vi
chng trnh ph thuc vo cc chui ny, bn nn ch dng ty chn ny
nu bn r bn ang lm g.
Mt chng trnh khng chy nhanh hn khi n c c t mt tp tin
.pyc hay .pyo so vi khi n c c t tp tin .py ; mt im nhanh hn
duy nht cc tp tin .pyc hay .pyo l tc chng c np.
Khi mt kch bn c chy bng cch nhp tn n dng lnh, th m
byte ca kch bn khng bao gi c ghi vo tp tin .pyc hay .pyo . Do
, thi gian khi ng ca mt kch bn c th c gim xung bng
cch chuyn hu ht m ca n thnh m-un v to mt kch bn nh
nhp m-un . Bn cng c th chy tp tin .pyc hay .pyo trc tip t
dng lnh.
C th dng tp tin spam.pyc (hay spam.pyo khi -O c dng) v khng
c tp tin spam.py ca cng mt m-un. Vic ny c tn dng phn
phi mt th vin Python di mt dng hi kh dch ngc.
M-un compileall c th to cc tp tin .pyc (hoc cc tp tin .pyo khi
-O c dng) cho mi m-un trong mt th mc.
Hai bin ny ch c nh ngha khi trnh thng dch chy ch tng tc.
4 of 10
08/31/2011 10:26 AM
6. M-un
http://www.vithon.org/tutorial/2.5/node8.html
6.3 dir() hm
Hm c sn dir() c dng tm cc tn mt m-un nh ngha. N tr v
mt danh sch cc chui sp xp:
>>> import fibo, sys
>>> dir(fibo)
['__name__', 'fib', 'fib2']
>>> dir(sys)
['__displayhook__', '__doc__', '__excepthook__', '__name__', '__stderr__',
'__stdin__', '__stdout__', '_getframe', 'api_version', 'argv',
'builtin_module_names', 'byteorder', 'callstats', 'copyright',
'displayhook', 'exc_clear', 'exc_info', 'exc_type', 'excepthook',
'exec_prefix', 'executable', 'exit', 'getdefaultencoding', 'getdlopenflags',
'getrecursionlimit', 'getrefcount', 'hexversion', 'maxint', 'maxunicode',
'meta_path', 'modules', 'path', 'path_hooks', 'path_importer_cache',
'platform', 'prefix', 'ps1', 'ps2', 'setcheckinterval', 'setdlopenflags',
'setprofile', 'setrecursionlimit', 'settrace', 'stderr', 'stdin', 'stdout',
'version', 'version_info', 'warnoptions']
5 of 10
08/31/2011 10:26 AM
6. M-un
http://www.vithon.org/tutorial/2.5/node8.html
6.4 Gi
Gi (package) l mt cch cu trc vng tn m-un ca Python bng cch
dng ``tn m-un c chm''. V d, tn m-un A.B ch ra m-un con tn "B"
trong mt gi tn "A". Cng nh vic s dng m-un gip tc gi ca cc
m-un khc nhau khng phi lo lng v cc bin ton cc ca nhau, vic s
dng tn m-un c chm gip tc gi ca cc gi a m-un nh NumPy hay
Python Imaging Library khng phi lo lng v tn m-un ca h.
Gi s bn mun thit k mt tp hp cc m-un (mt ``gi'') nhm vo vic
x l cc tp tin v d liu m thanh. C nhiu nh dng tp tin m thanh
(thng c nhn dng da vo phn m rng, v d: .wav, .ai, .au), do
bn s cn to v duy tr mt tp hp lun tng ca cc m-un cho vic
chuyn i gia cc nh dng khc nhau. Cng c nhiu tc v khc nhau bn
mun thc hin vi d liu m thanh (v d nh tng hp, thm ting vang, p
dng chc nng lm bng, to ra hiu ng ni), do bn s khng ngng vit
mt lot cc m-un thc hin cc tc v ny. Sau y l mt cu trc minh
ha cho gi ca bn (c trnh by theo cch ca mt h tp tin phn cp)
Sound/
__init__.py
Formats/
__init__.py
wavread.py
wavwrite.py
aiffread.py
aiffwrite.py
auread.py
auwrite.py
...
6 of 10
Top-level package
Initialize the sound package
Subpackage for file format conversions
08/31/2011 10:26 AM
6. M-un
http://www.vithon.org/tutorial/2.5/node8.html
Effects/
__init__.py
echo.py
surround.py
reverse.py
...
Filters/
__init__.py
equalizer.py
vocoder.py
karaoke.py
...
Mt bin th khc l nhp hm hoc bin mnh mun mt cch trc tip:
from Sound.Effects.echo import echofilter
Lu rng khi s dng from package import item, item c th hoc l m-un
con (hoc gi con) ca gi, hoc l mt tn no khc c nh ngha trong
7 of 10
08/31/2011 10:26 AM
6. M-un
http://www.vithon.org/tutorial/2.5/node8.html
gi, chng hn nh mt hm, lp, hoc bin. Cu lnh import trc ht kim
tra xem item c c nh ngha trong gi; nu khng, n gi nh rng l
m-un v th np n. Nu khng th tm thy m-un, bit l ImportError s
c nng.
Ngc li, khi dng c php nh import item.subitem.subsubitem, mi tiu mc tr
tiu mc cui phi l mt gi; tiu mc cui c th l mt m-un hoc mt gi
nhng khng th l mt lp, hay hm, hay bin c nh ngha trong tiu mc
trc.
6.4.1 Nhp * t mt gi
By gi chuyn g xy ra khi bn vit from Sound.Effects import *? Tt
nht, bn s hy vng m ny s tm cc m-un c trong gi v nhp tt c
chng vo. ng tic l tc v ny khng chy n nh lm trn h Mac v
Windows v h thng tp tin khng lun cha thng tin chnh xc v phn bit
hoa/thng trong tn tp tin. Trn cc h ny, khng c cch no bo m
bit c nu mt tp tin ECHO.PY cn c nhp vo nh l mt m-un echo,
Echo hay ECHO. (V d, Windows 95 c mt thi quen l hin mi tn tp tin vi
k t u tin vit hoa.) Hn ch tn 8+3 ca DOS cng to ra thm mt vn
th v vi cc tn m-un di.
Gii php duy nht l tc gi gi ch nh r ch mc ca gi. Cu lnh
import dng cch thc sau: nu m __init__.py ca gi c nh ngha mt danh
sch tn __all__, n s c dng lm danh sch ca cc tn m-un cn
c nhp khi gp from package import * . Tc gi gi s phi t cp nht
danh sch ny mi khi phin bn mi ca gi c pht hnh. Tc gi gi cng
c th khng h tr n, nu h khng thy cch dng importing * l hu dng
i vi gi ca h. V d, tp tin Sounds/Eects/__init__.py c th cha on m
sau:
__all__ = ["echo", "surround", "reverse"]
08/31/2011 10:26 AM
6. M-un
http://www.vithon.org/tutorial/2.5/node8.html
08/31/2011 10:26 AM
6. M-un
http://www.vithon.org/tutorial/2.5/node8.html
Ghi ch
6.1
... u .
Tht ra cc nh ngha hm cng l `cc cu lnh' c `thc thi'; vic
thc thi cu lnh ny nhp tn hm vo bng k hiu ton cc ca
m-un.
Phin bn 2.5, ti liu c cp nht ngy 19, thng 09, nm 2006.
Xem V ti liu ny... v cch ngh thay i.
10 of 10
08/31/2011 10:26 AM
7. Vo v ra
http://www.vithon.org/tutorial/2.5/node9.html
Bi ch dn Python
7. Vo v ra
C nhiu cc th hin u ra ca mt chng trnh; d liu c th c in ra
dng ngi c c, hoc vit vo mt tp tin dng sau ny. Chng ny s
bn v mt vi kh nng .
7.1 nh dng ra p hn
Chng ta gp hai cch vit gi tr: cu lnh biu thc v cu lnh print .
(Cch th ba l dng phng thc write() ca i tng tp tin; tp tin u ra
chun c th c tham chiu ti theo sys.stdout. Xem Tham kho th vin
Python bit thm chi tit.)
Thng thng bn s mun iu khin cch nh dng u ra ca bn nhiu hn
l ch n gin l in cc gi tr phn cch bi khong trng. C hai cch nh
dng u ra ca bn; cch th nht l bn t x l cc chui; dng php ct
ming ca chui v php ghp chui bn c th to bt k b cc no bn c th
ngh ra. M-un chun string cha mt vi cng c m chui kht vo chiu
ngang ct; chng ta s xem xt n lt na. Cch th hai l dng ton t % vi
mt chui l thng s bn tri. Ton t % thng dch thng s tri nh l mt
chui nh dng kiu sprintf() (nh trong C) p dng vo thng s bn
phi; v tr v mt chui t tc v nh dng ny.
Mt cu hi vn cn : lm sao chuyn gi tr thnh chui? May mn thay
Python c mt cch chuyn bt k gi tr no thnh chui: truyn n vo hm
repr() hay hm str() . Du nhy ngc (``) tng ng vi repr(), nhng
chng khng cn c dng trong m Python mi, v rt c th s khng cn
trong cc phin bn ngn ng sau ny.
str() nhm tr v cch th hin gi tr mt cch d c, trong khi repr()
nhm to cch th hin m trnh thng dch c th c (hoc s sinh li
SyntaxError nu khng c c php tng ng). i vi cc i tng khng
c cch th hin cho ngi c, str() s tr v cng gi tr nh repr(). Nhiu
gi tr, v d nh s, hoc cu trc nh danh sch v t in, c cng cch th
hin vi c hai hm ny. Ring chui v s chm ng c hai cch th hin khc
bit.
Mt vi v d:
>>> s = 'Hello, world.'
>>> str(s)
'Hello, world.'
>>> repr(s)
"'Hello, world.'"
1 of 7
08/31/2011 10:26 AM
7. Vo v ra
http://www.vithon.org/tutorial/2.5/node9.html
>>> 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'))"
2 of 7
08/31/2011 10:26 AM
7. Vo v ra
http://www.vithon.org/tutorial/2.5/node9.html
3 of 7
08/31/2011 10:26 AM
7. Vo v ra
http://www.vithon.org/tutorial/2.5/node9.html
08/31/2011 10:26 AM
7. Vo v ra
http://www.vithon.org/tutorial/2.5/node9.html
08/31/2011 10:26 AM
7. Vo v ra
http://www.vithon.org/tutorial/2.5/node9.html
>>> f.read(1)
'5'
>>> f.seek(-3, 2) # Go to the 3rd byte before the end
>>> f.read(1)
'd'
(C nhng bin th khc, dng khi gim nhiu i tng hoc khi bn khng
mun vit d liu gim vo tp tin; tham kho ton b ti liu v pickle
trong Tham kho th vin Python.)
pickle l cch chun lm cho cc i tng Python c th c lu v dng
li bi cc chng trnh khc, hoc bi ln chy khc ca cng chng trnh;
6 of 7
08/31/2011 10:26 AM
7. Vo v ra
http://www.vithon.org/tutorial/2.5/node9.html
7 of 7
08/31/2011 10:26 AM
8. Li v bit l
http://www.vithon.org/tutorial/2.5/node10.html
Bi ch dn Python
8. Li v bit l
n by gi chng ta cng ch mi nhc n cc thng ip li, nhng nu bn
th qua cc v d th bn c th gp nhiu hn. C (t nht) hai loi li khc bit:
li c php v bit l.
8.1 Li c php
Li c php, cn bit n nh li phn tch (parsing error), c l l phn nn ln nht
bn gp phi khi vn ang hc Python:
>>> while True print 'Hello world'
File "<stdin>", line 1, in ?
while True print 'Hello world'
^
SyntaxError: invalid syntax
8.2 Bit l
Cho d mt cu lnh hoc biu thc l ng n, n vn c th to li khi thc thi.
Nhng li b pht hin trong lc thc thi c gi l bit l v khng tai hi mt
cch v iu kin: bn s hc cch x l chng trong cc chng trnh Python. Hu
ht cc bit l u c x l bi chng trnh v dn n kt qu l cc thng ip
li nh y:
>>> 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
Dng cui cng ca thng ip li cho bit chuyn g xy ra. Bit l c nhiu kiu, v
kiu c hin th nh l mt phn ca thng ip: cc kiu trong v d l
ZeroDivisionError, NameError v TypeError. Chui c hin th nh l kiu bit
l l tn ca bit l c sn va xy ra. iu ny ng vi tt c cc bit l c sn,
1 of 7
08/31/2011 10:27 AM
8. Li v bit l
http://www.vithon.org/tutorial/2.5/node10.html
8.3 X l bit l
Chng ta c th vit nhng chng trnh x l nhng bit l c chn. Hy xem v
d sau, n yu cu ngi dng nhp vo d liu cho ti khi mt s nguyn c
nhp, nhng cng cho php ngi dng ngng chng trnh (dng Control-C hoc
phm tt khc m h iu hnh h tr); lu rng s ngt qung do ngi dng to
nn c nh du bi vic nng bit l KeyboardInterrupt .
>>> while True:
...
try:
...
x = int(raw_input("Please enter a number: "))
...
break
...
except ValueError:
...
print "Oops! That was no valid number. Try again..."
...
2 of 7
08/31/2011 10:27 AM
8. Li v bit l
http://www.vithon.org/tutorial/2.5/node10.html
try ... except (cu lnh) c mt v elsekhng bt buc, m khi c mt s phi i sau
tt c cc v except. N dng cho m s c thc thi nu v try khng nng bit l
no. V d:
for arg in sys.argv[1:]:
try:
f = open(arg, 'r')
except IOError:
print 'cannot open', arg
else:
print arg, 'has', len(f.readlines()), 'lines'
f.close()
3 of 7
08/31/2011 10:27 AM
8. Li v bit l
...
print inst
...
x, y = inst
...
print 'x =', x
...
print 'y =', y
...
<type 'instance'>
('spam', 'eggs')
('spam', 'eggs')
x = spam
y = eggs
http://www.vithon.org/tutorial/2.5/node10.html
# __str__ allows args to printed directly
# __getitem__ allows args to be unpacked directly
4 of 7
08/31/2011 10:27 AM
8. Li v bit l
http://www.vithon.org/tutorial/2.5/node10.html
5 of 7
08/31/2011 10:27 AM
8. Li v bit l
http://www.vithon.org/tutorial/2.5/node10.html
"""
A v nally lun c thc thi trc khi ri khi cu lnh try , cho d c xy ra bit
l hay khng. Khi mt bit l xy ra trong v try v khng c x l bi v
except (hoc n xy ra trong mt v except hay else ), n s c nng li sau
khi v finally c thc thi. V finally cng c thc thi ``trn ng ra'' khi
bt k v no ca cu lnh try c b li thng qua cu lnh break, continue hay
return . Mt v d phc tp hn:
>>> def divide(x, y):
...
try:
...
result = x / y
...
except ZeroDivisionError:
...
print "division by zero!"
...
else:
...
print "result is", result
...
finally:
...
print "executing finally clause"
...
>>> divide(2, 1)
result is 2
executing finally clause
>>> divide(2, 0)
6 of 7
08/31/2011 10:27 AM
8. Li v bit l
http://www.vithon.org/tutorial/2.5/node10.html
division by zero!
executing finally clause
>>> divide("2", "1")
executing finally clause
Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "<stdin>", line 3, in divide
TypeError: unsupported operand type(s) for /: 'str' and 'str'
8.7 nh ngha x l c sn
Mt s i tng nh ngha cc tc v dn dp chun thc thi khi mt i tng
khng cn c cn n, cho d vic x dng i tng l thnh cng hay tht bi.
Xem qua v d sau, n th m mt tp tin v vit ni dung ca n ra mn hnh.
for line in open("myfile.txt"):
print line
Sau khi cu lnh c thc thi, tp tin f lun c ng li, cho d gp phi vn
trong khi x l cc dng. Cc i tng khc m cung cp nhng tc v dn dp nh
ngha sn s cho bit v im ny trong ti liu ca chng.
Phin bn 2.5, ti liu c cp nht ngy 19, thng 09, nm 2006.
Xem V ti liu ny... v cch ngh thay i.
7 of 7
08/31/2011 10:27 AM
9. Lp
http://www.vithon.org/tutorial/2.5/node11.html
Bi ch dn Python
9. Lp
Ch cn mt t c php v t kha mi, Python c th h tr lp. N l s trn ln
gia C++ v Modula-3. Cng nh m-un, cc lp tron Python khng t ro cn
tuyt i gia nh ngha lp v ngi s dng, m thay vo n da vo s lch
thip trong cch dng m ``khng ph nh ngha.'' Tuy nhin, cc tnh nng quan
trng nht ca lp vn c gi li trn vn: cch k tha lp h tr nhiu lp c s, lp
con c th nh ngha li bt k phng thc no ca cc lp c s ca n, v mt
phng thc c th gi mt phng thc cng tn ca mt lp c s. Cc i tng c
th cha mt lng d liu ring bt k.
Theo thut ng C++, mi thnh vin lp (k c thnh vin d liu) l public(cng
cng), v mi thnh vin hm l virtual(o). Khng c b khi to (constructor) hoc
b hy (destructor) c bit. Cng nh Modula-3, khng c cch vit tt no tham
chiu ti cc thnh vin ca mt i tng t cc phng thc ca n: hm phng
thc c khai bo vi thng s th nht th hin chnh i tng , v c t ng
truyn vo qua lnh gi. Nh trong Smalltalk, cc lp cng l cc i tng theo mt
ngha rng: trong Python, mi kiu d liu l u l cc i tng. iu ny cho php
nhp (import) v i tn. Khng nh C++ v Modula-3, cc kiu c sn c th c
dng nh cc lp c s m rng bi ngi dng. V nh trong C++ nhng khng
ging Modula-3, a s cc ton t c sn vi c php c bit (cc ton t s hc, truy
cp mng, v.v...) c th c nh ngha li trong cc trng hp c th ca lp.
9.1 Vi li v thut ng
Nhng t chuyn ngnh dng y theo t vng ca Smalltalk v C++.
Cc i tng c tnh c th (individuality), v nhiu tn (trong nhiu phm vi, scope)
c th c gn vo cng mt i tng. Trong cc ngn ng khc c gi l tn
lng (alias). N thng khng c nhn ra khi dng Python ln u, v c th c
b qua khi lm vic vi cc kiu bt bin c bn (s, chui, b). Tuy nhin, tn lng c
mt nh hng i vi ngha ca m Python c s dng cc i tng kh bin nh
danh sch, t in, v a s cc kiu th hin cc vt ngoi chng trnh (tp tin, ca
s, v.v...). N thng c dng v tn lng c tc dng nh l con tr theo mt vi
kha cnh no . V d, truyn mt i tng vo mt hm r v ch c con tr l
c truyn, v nu mt hm thay i mt i tng c truyn vo, th ni gi s
thy cc thay i -- thay v cn hai kiu truyn thng s nh trong Pascal.
1 of 13
08/31/2011 10:27 AM
9. Lp
http://www.vithon.org/tutorial/2.5/node11.html
vng tn!
9.1
08/31/2011 10:27 AM
9. Lp
http://www.vithon.org/tutorial/2.5/node11.html
nh ngha lp, cng nh nh ngha hm (cu lnhdef ) phi c thc thi trc khi
chng c hiu lc. (Bn c th t mt nh ngha hm trong mt nhnh ca lnh if ,
hoc trong mt hm.)
Trong thc t, cc cu lnh trong mt nh ngha lp thng l nh ngha hm,
nhng cc cu lnh khc cng c cho php, v i khi rt hu dng. Cc nh
ngha hm trong mt lp thng c mt dng danh sch thng s l, v phi tun theo
cch gi phng thc.
Khi gp phi mt nh ngha lp, mt vng tn mi c to ra, v c dng nh l
phm vi ni b -- do , mi php gn vo cc bin ni b i vo vng tn ny. c
bit, cc nh ngha hm buc tn ca hm mi y.
Khi ri khi mt nh ngha lp mt cch bnh thng, mt i tng lp c to ra.
y c bn l mt b gi (wrapper) ca ni dung ca vng tn to ra bi nh ngha
lp. Phm vi ni b ban u (trc khi vo nh ngha lp) c thit lp li, v i
tng lp c buc vo y qua tn lp ch nh nh ngha lp, (ClassName
trong v d ny).
3 of 13
08/31/2011 10:27 AM
9. Lp
http://www.vithon.org/tutorial/2.5/node11.html
9.3.2 i tng lp
Cc i tng lp h tr hai loi tc v: tham chiu thuc tnh v to trng hp
(instantiation).
Tham chiu thuc tnh dng c php chun c dng cho mi tham chiu thuc tnh
trong Python: obj.name. Cc tn thuc tnh hp l gm mi tn trong vng tn ca
lp khi i tng lp c to ra. Do , nu nh ngha lp c dng nh sau:
class MyClass:
"A simple example class"
i = 12345
def f(self):
return 'hello world'
08/31/2011 10:27 AM
9. Lp
http://www.vithon.org/tutorial/2.5/node11.html
Loi tham chiu thuc tnh trng hp khc l mt method (phng thc). Mt
phng thc l mt hm ``ca'' mt i tng. (Trong Python, t phng thc khng
ch ring cho trng hp lp: cc kiu i tng khc cng c th c phng thc. V
d, i tng danh sch c phng thc tn append, insert, remove, sort, v.v... Tuy
nhin, trong phn sau chng ta s ch dng t phng thc d ch cc phng thc
ca i tng trng hp lp, tr khi c ch nh khc i.)
Cc tn phng thc hp l ca mt i tng trng hp ph thuc vo lp ca n.
Theo nh ngha, mi thuc tnh ca mt lp m l nhng i tng hm nh ngha
cc phng thc tng ng ca cc trng hp ca lp . Trong v d ca chng ta,
x.f l mt tham chiu phng thc hp l, v MyClass.f l mt hm, nhng x.i
khng phi, bi v MyClass.i khng phi. Nhng x.f khng phi l mt th nh
MyClass.f -- n l mt method object (i tng phng thc), khng phi l mt i
tng hm.
Trong MyClass , n s tr v chui 'hello world'. Tuy nhin, cng khng nht thit
phi gi mt phng thc ngay lp tc: x.f l mt i tng phng thc, v c th
c ct i v gi vo mt thi im khc. V d:
xf = x.f
while True:
print xf()
08/31/2011 10:27 AM
9. Lp
http://www.vithon.org/tutorial/2.5/node11.html
9.4 Mt vi li bnh
Thuc tnh d liu s che thuc tnh phng thc cng tn; trnh v tnh trng lp
tn, m c th dn n cc li rt kh tm ra trong cc chng trnh ln, bn nn c
mt quy nh t tn no gim thiu t l trng lp. Cc quy nh kh thi c th
gm vit hoa tn phng thc, t tin t vo cc tn thuc tnh d liu (v d nh du
gch di _), hoc dng ng t cho phng thc v danh t cho cc thuc tnh d
liu.
Cc thuc tnh d liu c th c tham chiu ti bi c phng thc ln ngi dng
i tng . Ni mt cch khc, lp khng th c dng ci t cc kiu d liu
tru tng tuyt i. Trong thc t, khng c g trong Python c th p vic che du
d liu -- tt c u da trn nguyn tc. (Mt khc, ci t Python, c vit bng C,
c th du cc chi tit ci t v iu khin truy cp vo mt i tng nu cn; iu
ny c th c dng trong cc b m rng Python vit bng C.)
Ngi dng nn dng cc thuc tnh d liu mt cch cn thn -- ngi dng c th
ph hng nhng bt bin (invariant) c gi bi cc phng thc nu c sa cc
thuc tnh d liu. Lu rng ngi dng c th thm cc thuc tnh d liu ring
ca h vo i tng trng hp m khng lm nh hng tnh hp l ca cc phng
thc, min l khng c trng lp tn -- xin nhc li, mt quy tc t tn c th gim
bt s au u y.
Khng c cch ngn gn tham chiu ti thuc tnh d liu (hoc cc phng thc
khc!) t trong phng thc. iu ny tht ra gip chng ta d c m v khng c s
ln ln gia bin ni b v bin trng hp.
Thng s u tin ca phng thc thng c gi l self. y cng ch l mt quy
c: tn self hon ton khng c ngha c bit trong Python. (Tuy nhin xin nh
nu bn khng theo quy c th m ca bn s c th tr nn kh c i vi ngi
khc, v c th l trnh duyt lp c vit da trn nhng quy c nh vy.)
Bt k i tng hm no m l thuc tnh ca mt lp s nh ngha mt phng
thc cho cc trng hp ca lp . Khng nht thit nh ngha hm phi nm trong
nh ngha lp trn vn bn: gn mt i tng hm vo mt bin ni b trong lp
cng c. V d:
# Function defined outside the class
def f1(self, x, y):
return min(x, x+y)
class C:
6 of 13
08/31/2011 10:27 AM
9. Lp
http://www.vithon.org/tutorial/2.5/node11.html
f = f1
def g(self):
return 'hello world'
h = g
9.5 K tha
D nhin, mt tnh nng ngn ng s khng ng c gi l ``lp'' nu n khng h
tr k tha. C php ca mt nh ngha lp con nh sau:
class DerivedClassName(BaseClassName):
<statement-1>
.
.
.
<statement-N>
08/31/2011 10:27 AM
9. Lp
http://www.vithon.org/tutorial/2.5/node11.html
9.5.1 a k tha
Python cng h tr mt dng a k tha hn ch. Mt nh ngha lp vi nhiu lp c
s c dng sau:
class DerivedClassName(Base1, Base2, Base3):
<statement-1>
.
.
.
<statement-N>
Lut duy nht cn gii thch ngha l lut gii cc tham chiu thuc tnh ca lp.
N tun theo lut tm theo chiu su, v tm tri qua phi. Do , nu mt thuc tnh
khng c tm ra trong DerivedClassName, n s c tm trong Base1, ri ( quy)
trong cc lp c s ca Base1, ri ch khi n khng c tm thy, n s c tm
trong Base2, v c nh vy.
(i vi mt s ngi tm theo chiu rng -- tm Base2 v Base3 trc cc lp c s ca
Base1 -- c v t nhin hn. Nhng, iu ny yu cu bn bit mt thuc tnh no
ca Base1 c tht s nh ngha trong Base1 hay trong mt trong cc lp c s ca
n trc khi bn c th bit c hu qu ca s trng lp tn vi mt thuc tnh ca
Base2. Lut tm theo chiu su khng phn bit gia thuc tnh trc tip hay k tha
ca Base1.)
Ai cng bit rng vic dng a k tha ba bi l mt cn c mng cho bo tr, c
bit l Python da vo quy c trnh trng lp tn. Mt vn c bn vi a k
tha l mt lp con ca hai lp m c cng mt lp c s. Mc d d hiu chuyn g
xy ra trong vn ny (trng hp s c mt bn chp duy nht ca ``cc bin
trng hp'' ca cc thuc tnh d liu dng bi lp c s chung), n khng r cho
lm nu cc ngha ny tht s hu ch.
08/31/2011 10:27 AM
9. Lp
http://www.vithon.org/tutorial/2.5/node11.html
08/31/2011 10:27 AM
9. Lp
http://www.vithon.org/tutorial/2.5/node11.html
raise Class, instance
raise instance
9.9 B lp
By gi c l bn lu rng hu ht cc i tng cha (container object) c th
c lp qua bng cu lnh 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
Kiu truy xut ny r rng, xc tch, v tin li. B lp (iterator) c dng khp ni
10 of 13
08/31/2011 10:27 AM
9. Lp
http://www.vithon.org/tutorial/2.5/node11.html
9.10 B to
B sinh (generator) l mt cng c n gin v mnh m to cc b lp. Chng
c vit nh nhng hm thng thng nhng dng cu lnh yield khi no chng
mun tr v d liu. Mi ln next() c gi, b sinh tr li ni n thot ra (n nh
11 of 13
08/31/2011 10:27 AM
9. Lp
http://www.vithon.org/tutorial/2.5/node11.html
# sum of squares
# dot product
12 of 13
08/31/2011 10:27 AM
9. Lp
http://www.vithon.org/tutorial/2.5/node11.html
>>> list(data[i] for i in range(len(data)-1,-1,-1))
['f', 'l', 'o', 'g']
Ghi ch
... vng tn!9.1
Tr mt chuyn. Cc i tng m-un c mt thuc tnh ch c gi l
__dict__ tr v mt t in dng ci t vng tn ca m-un; tn __dict__
l mt thuc tnh nhng khng phi l mt tn ton cc. R rng, s dng n vi
phm tnh tru tng ca ci t vng tn, v nn c gii hn vo nhng
chuyn nh g ri.
Phin bn 2.5, ti liu c cp nht ngy 19, thng 09, nm 2006.
Xem V ti liu ny... v cch ngh thay i.
13 of 13
08/31/2011 10:27 AM
http://www.vithon.org/tutorial/2.5/node12.html
Bi ch dn Python
Nh dng kiu lnh "import os" thay v "from os import *". iu ny khin cho
os.open() khng che hm open() sn c ca python. Hai hm ny hot ng khc
nhau rt nhiu.
Cc hm sn c dir() v help() l cc cng c tr gip tng tc hu ch khi lm vic
vi cc m-un ln nh os:
>>> import os
>>> dir(os)
<returns a list of all module functions>
>>> help(os)
<returns an extensive manual page created from the module's docstrings>
1 of 5
08/31/2011 10:28 AM
http://www.vithon.org/tutorial/2.5/node12.html
Cch thot khi mt kch bn mt cch trc tip nht l dng "sys.exit()".
10.6 Ton hc
math (m-un) cung cp cc hm x l v ton du chm ng ca th vin C mc di:
>>> import math
>>> math.cos(math.pi / 4.0)
0.70710678118654757
>>> math.log(1024, 2)
10.0
2 of 5
08/31/2011 10:28 AM
http://www.vithon.org/tutorial/2.5/node12.html
>>> random.random()
# random float
0.17970987693706186
>>> random.randrange(6)
# random integer chosen from range(6)
4
10.8 Ngy v gi
datetime (m-un) cung cp cc lp dnh cho vic x l ngy thng v thi gian t n
gin ti phc tp. M-un ny c h tr cc php ton v ngy thng, tuy nhin n ch
trng ti vic truy cp cc thnh phn ngy thng mt cch hiu qu gip cho vic nh
dng chng. M-un ny cng h tr cc i tng c th phn bit c cc vng thi
gian.
# 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
10.9 Nn d liu
Python cung cp mt s m-un h tr trc tip cc nh dng nn v lu tr d liu ph
3 of 5
08/31/2011 10:28 AM
http://www.vithon.org/tutorial/2.5/node12.html
4 of 5
08/31/2011 10:28 AM
import doctest
doctest.testmod()
http://www.vithon.org/tutorial/2.5/node12.html
10.12 Km c pin
Python c gn vi tng ``km pin''. iu ny c th hin bi cc tnh nng mnh
m v a dng ca cc gi ln hn ca n. V d nh:
xmlrpclib v SimpleXMLRPCServer (m-un) gip cho vic ci t cc lnh gi
th tc t xa (remote procedure call) tr nn d dng hn bao gi ht. Khc vi ci
tn, chng ta c th s dng m-un ny m khng cn cc kin thc c th v x l
XML.
email (gi) l mt th vin h tr vic qun l cc th in t, bao gm cc vn
bn MIME v cc vn bn da trn RFC 2822 khc. Khng trc tip gi v nhn
thng ip nh smtplib v poplib , gi email c mt tp cc cng c dnh cho
vic xy dng v m ha cc cu trc thng ip phc tp (bao gm c tp tin nh
km) v ci t m ha internet v giao thc tiu .
xml.dom v xml.sax (gi) h tr rt tt cho vic phn tch nh dng ph bin ny.
Tng t, m-un csv h tr vic c ghi trc tip trn mt nh dng vn bn
chung. Kt hp li, cc m-un v gi k trn n gin ha rt nhiu vic trao i
d liu gia cc trnh ng dng ca python v cc chng trnh khc.
Vic h tr quc t ha c thc hin bi mt vi m-un, bao gm gettext,
locale, v gi codecs .
Phin bn 2.5, ti liu c cp nht ngy 19, thng 09, nm 2006.
Xem V ti liu ny... v cch ngh thay i.
5 of 5
08/31/2011 10:28 AM
http://www.vithon.org/tutorial/2.5/node13.html
Bi ch dn Python
11.1 nh dng ra
repr (m-un)cung cp mt phin bn repr() c ty bin hin th vn tt cc
i tng cha (container) ln hoc lng nhau nhiu mc:
>>> import repr
>>> repr.repr(set('supercalifragilisticexpialidocious'))
"set(['a', 'c', 'd', 'e', 'f', 'g', ...])"
1 of 7
08/31/2011 10:30 AM
http://www.vithon.org/tutorial/2.5/node13.html
11.2 To mu
string (m-un) cung cp mt lp Template vi mt c php n gin, c th d dng
thay i bi ngi dng. iu ny cho php ngi dng c th ty bin trnh ng dng
m khng phi thay i n.
nh dng ny s dng cc tn bin gi ch bt u vi "$" sau l mt tn bin hp l
ca Python (ch ci, ch s v du gch di). Tn gi ch c t trong ngoc, iu
ny khin n c th c ni tip bi cc k t khc m khng cn c khong trng
gia. Vit "$$" s to ra mt k t thot n "$":
>>> 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.'
')
>>> t = BatchRename(fmt)
>>> date = time.strftime('%d%b%y')
>>> for i, filename in enumerate(photofiles):
...
base, ext = os.path.splitext(filename)
2 of 7
08/31/2011 10:30 AM
http://www.vithon.org/tutorial/2.5/node13.html
Mt ng dng khc ca to mu l vic tch bit l-gc chng trnh ra khi cc chi tit
v cc nh dng u ra khc nhau. iu ny gip cho vic thay th cc khun mu ty
bin cho cc tp tin XML, cc bo co bng vn bn thng thng v cc bo co bng
HTML.
11.4 a lung
Phn lung l k thut phn tch cc tc v khc nhau ca mt chng trnh khi chng
khng b rng buc trt t vi nhau. Cc lung c s dng tng tnh p ng ca
cc chng trnh ng dng i hi vic nhp liu t ngi dng din ra cng lc vi cc
tin trnh nn khc. Mt trng hp tng t l vic chy cc tc v vo ra song song
vi cc tc v tnh ton mt lung khc.
on m sau y minh ha cch m-un threading chy cc tc v nn trong khi
chng trnh chnh vn ang chy:
import threading, zipfile
class AsyncZip(threading.Thread):
def __init__(self, infile, outfile):
threading.Thread.__init__(self)
self.infile = infile
self.outfile = outfile
3 of 7
08/31/2011 10:30 AM
http://www.vithon.org/tutorial/2.5/node13.html
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.'
11.5 Nht k
logging (m-un) cung cp mt h thng ghi nht k (logging) linh hot v c y
cc tnh nng. Trong trng hp n gin nht, mt thng ip nht k c gi ti mt
tp tin hay ti sys.stderr:
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')
Theo mc nh, cc thng ip cha thng tin dnh cho vic g ri b chn li v u ra
c gi ti knh bo li chun. Cc thng ip ny cn c th c chuyn tip ti th
in t, gi tin, socket hay my ch HTTP. Cc b lc c th chn cc c ch chuyn tip
ty theo mc u tin ca thng ip: DEBUG, INFO, WARNING, ERROR, v CRITICAL.
H thng nht k c th c cu hnh trc tip bn trong Python hoc np t mt tp
tin cu hnh m ngi dng c th sa i c, nhm ty bin vic ghi nht k m
khng phi sa i trnh ng dng.
08/31/2011 10:30 AM
http://www.vithon.org/tutorial/2.5/node13.html
08/31/2011 10:30 AM
http://www.vithon.org/tutorial/2.5/node13.html
Ngoi cc cu trc thay th cho danh sch, th vin chun cn cung cp cc cng c
nh m-un bisect cha cc hm thao tc trn danh sch c sp xp:
>>> 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')]
6 of 7
08/31/2011 10:30 AM
http://www.vithon.org/tutorial/2.5/node13.html
Decimal("0.7350")
>>> .70 * 1.05
0.73499999999999999
7 of 7
08/31/2011 10:30 AM
http://www.vithon.org/tutorial/2.5/node14.html
Bi ch dn Python
08/31/2011 10:50 AM
http://www.vithon.org/tutorial/2.5/node14.html
ISBN 0-596-00797-3.)
hi cc cu hi lin quan ti Python v thng bo li, bn c th gi vi
nhm tin comp.lang.python, hoc gi chng ti danh sch th tn pythonlist@python.org. Nhm tin v danh sch th tn c ni chung vi nhau, nn
cc tin gi ni ny s t ng c mt ni kia. C khong 120 bi gi mt
ngy (cao nht l vi trm), hi (v tr li) cu hi, xut cc tnh nng mi,
v thng bo cc m-un mi. Trc khi gi, hy nh xem qua danh sch Cc
cu hi thng hi (Frequently Asked Question) (cn c gi l FAQ), hoc
xem qua th mc Misc/ ca bn phn phi ngun Python. Kho lu tr nhm
tin c http://mail.python.org/pipermail/. FAQ tr li nhiu cu hi hay gp
thng xuyn, v c th cu hi ca bn cng c trong ny.
Phin bn 2.5, ti liu c cp nht ngy 19, thng 09, nm 2006.
Xem V ti liu ny... v cch ngh thay i.
2 of 2
08/31/2011 10:50 AM
http://www.vithon.org/tutorial/2.5/node15.html
Python Tutorial
This Appendix was left untranslated.
08/31/2011 10:51 AM
http://www.vithon.org/tutorial/2.5/node15.html
The key bindings and some other parameters of the Readline library can be
customized by placing commands in an initialization le called ~/.inputrc. Key
bindings have the form
key-name: function-name
or
"string": function-name
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 lename 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 if you're accustomed to using Tab for that purpose.)
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
le: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 expression up to the nal "." and then suggest
completions from the attributes of the resulting object. Note that this may
execute application-dened code if an object with a __getattr__() method is
part of the expression.
A more capable startup le might look like this example. Note that this deletes
the names it creates once they are no longer needed; this is done since the
2 of 4
08/31/2011 10:51 AM
http://www.vithon.org/tutorial/2.5/node15.html
import
import
import
import
atexit
os
readline
rlcompleter
historyPath = os.path.expanduser("~/.pyhistory")
def save_history(historyPath=historyPath):
import readline
readline.write_history_file(historyPath)
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.
Footnotes
A.1
... le:
Python will execute the contents of a le identied by the PYTHONSTARTUP
environment variable when you start an interactive interpreter.
3 of 4
08/31/2011 10:51 AM
http://www.vithon.org/tutorial/2.5/node15.html
4 of 4
08/31/2011 10:51 AM
http://www.vithon.org/tutorial/2.5/node16.html
Python Tutorial
This Appendix was left untranslated.
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 dierence being that the rst 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 oating-point
numbers you enter are only approximated by the binary oating-point
numbers actually stored in the machine.
The problem is easier to understand at rst 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 of
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 innitely repeating fraction
1 of 5
08/31/2011 10:52 AM
http://www.vithon.org/tutorial/2.5/node16.html
0.0001100110011001100110011001100110011001100110011...
Stop at any nite 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 oating-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
>>> 0.1
0.1000000000000000055511151231257827021181583404541015625
instead! The Python prompt uses the builtin repr() function to obtain a
string version of everything it displays. For oats, repr(float) rounds the true
decimal value to 17 signicant digits, giving
0.10000000000000001
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
2 of 5
08/31/2011 10:52 AM
http://www.vithon.org/tutorial/2.5/node16.html
you may be tempted to use the round() function to chop it back to the single
digit you expect. But that makes no dierence:
>>> round(0.1, 1)
0.10000000000000001
The problem is that the binary oating-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, summing ten
values of 0.1 may not yield exactly 1.0, either:
>>> sum = 0.0
>>> for i in range(10):
...
sum += 0.1
...
>>> sum
0.99999999999999989
Binary oating-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 oating-point! The errors in Python oat operations are
inherited from the oating-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 oat operation can suer a new rounding
error.
While pathological cases do exist, for most casual use of oating-point
arithmetic you'll see the result you expect in the end if you simply round the
display of your nal results to the number of decimal digits you expect. str()
usually suces, and for ner control see the discussion of Python's % format
operator: the %g, %f and %e format codes supply exible and easy ways to
round oat results for display.
3 of 5
08/31/2011 10:52 AM
http://www.vithon.org/tutorial/2.5/node16.html
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 oating point arithmetic,
and almost all platforms map Python oats 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:
>>> 2**52
4503599627370496L
>>> 2**53
9007199254740992L
>>> 2**56/10
7205759403792793L
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(2**56, 10)
>>> r
6L
Since the remainder is more than half of 10, the best approximation is
obtained by rounding up:
>>> q+1
7205759403792794L
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!
4 of 5
08/31/2011 10:52 AM
http://www.vithon.org/tutorial/2.5/node16.html
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 * 2**56
7205759403792794.0
If we multiply that fraction by 10**30, we can see the (truncated) value of its
30 most signicant decimal digits:
>>> 7205759403792794 * 10**30 / 2**56
100000000000000005551115123125L
5 of 5
08/31/2011 10:52 AM
http://www.vithon.org/tutorial/2.5/node17.html
Python Tutorial
This Appendix was left untranslated.
1 of 13
08/31/2011 10:54 AM
Release
2.2.2
2.2.3
2.3
2.3.1
2.3.2
2.3.3
2.3.4
2.3.5
2.4
2.4.1
2.4.2
2.4.3
2.5
http://www.vithon.org/tutorial/2.5/node17.html
Derived from
Year
2.2.1
2002
2.2.2
2002-2003
2.2.2
2002-2003
2.3
2002-2003
2.3.1
2003
2.3.2
2003
2.3.3
2004
2.3.4
2005
2.3
2004
2.4
2005
2.4.1
2005
2.4.2
2006
2.4
2006
Owner
PSF
PSF
PSF
PSF
PSF
PSF
PSF
PSF
PSF
PSF
PSF
PSF
PSF
GPL compatible?
yes
yes
yes
yes
yes
yes
yes
yes
yes
yes
yes
yes
yes
Note: GPL-compatible doesn't mean that we're distributing Python under the
GPL. All Python licenses, unlike the GPL, let you distribute a modied 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.
08/31/2011 10:54 AM
http://www.vithon.org/tutorial/2.5/node17.html
08/31/2011 10:54 AM
http://www.vithon.org/tutorial/2.5/node17.html
08/31/2011 10:54 AM
http://www.vithon.org/tutorial/2.5/node17.html
08/31/2011 10:54 AM
http://www.vithon.org/tutorial/2.5/node17.html
6 of 13
08/31/2011 10:54 AM
http://www.vithon.org/tutorial/2.5/node17.html
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
3. The names of its contributors may not be used to endorse or promote
products derived from this software without specific prior written
permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
Any feedback is very welcome.
http://www.math.keio.ac.jp/matumoto/emt.html
email: matumoto@math.keio.ac.jp
C.3.2 Sockets
The socket module uses the functions, getaddrinfo, and getnameinfo, which
are coded in separate source les from the WIDE Project,
http://www.wide.ad.jp/about/index.html.
Copyright (C) 1995, 1996, 1997, and 1998 WIDE Project.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
3. Neither the name of the project nor the names of its contributors
may be used to endorse or promote products derived from this software
7 of 13
08/31/2011 10:54 AM
http://www.vithon.org/tutorial/2.5/node17.html
8 of 13
08/31/2011 10:54 AM
http://www.vithon.org/tutorial/2.5/node17.html
|
of California, and shall not be used for advertising or product
|
\ endorsement purposes.
/
---------------------------------------------------------------------
9 of 13
08/31/2011 10:54 AM
http://www.vithon.org/tutorial/2.5/node17.html
08/31/2011 10:54 AM
http://www.vithon.org/tutorial/2.5/node17.html
C.3.7 Proling
The profile and pstats modules contain the following notice:
Copyright 1994, by InfoSeek Corporation, all rights reserved.
Written by James Roskind
Permission to use, copy, modify, and distribute this Python software
and its associated documentation for any purpose (subject to the
restriction in the following sentence) without fee is hereby granted,
provided that the above copyright notice appears in all copies, and
that both that copyright notice and this permission notice appear in
supporting documentation, and that the name of InfoSeek not be used in
advertising or publicity pertaining to distribution of the software
without specific, written prior permission. This permission is
explicitly restricted to the copying and modification of the software
to remain in Python, compiled Python, or other languages (such as C)
wherein the modified or derived code is exclusively imported into a
Python module.
INFOSEEK CORPORATION DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS
SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
FITNESS. IN NO EVENT SHALL INFOSEEK CORPORATION 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.
08/31/2011 10:54 AM
http://www.vithon.org/tutorial/2.5/node17.html
12 of 13
08/31/2011 10:54 AM
http://www.vithon.org/tutorial/2.5/node17.html
13 of 13
08/31/2011 10:54 AM
D. Glossary
http://www.vithon.org/tutorial/2.5/node18.html
Python Tutorial
This Appendix was left untranslated.
D. Glossary
>>>
...
The typical Python prompt of the interactive shell. Often seen for code
examples that can be tried right away in the interpreter.
The typical Python prompt of the interactive shell when entering code for an
indented code block.
BDFL
Benevolent Dictator For Life, a.k.a. Guido van Rossum, Python's creator.
byte code
The internal representation of a Python program in the interpreter. The byte
code is also cached in .pyc and .pyo les so that executing the same le is
faster the second time (recompilation from source to byte code can be avoided).
This ``intermediate language'' is said to run on a ``virtual machine'' that calls
the subroutines corresponding to each bytecode.
classic class
Any class which does not inherit from object. See new-style class.
coercion
The implicit conversion of an instance of one type to another during an
operation which involves two arguments of the same type. For example,
int(3.15) converts the oating point number to the integer 3, but in 3+4.5,
each argument is of a dierent type (one int, one oat), and both must be
converted to the same type before they can be added or it will raise a
TypeError. Coercion between two operands can be performed with the coerce
builtin function; thus, 3+4.5 is equivalent to calling operator.add(*coerce(3,
4.5)) and results in operator.add(3.0, 4.5). Without coercion, all
arguments of even compatible types would have to be normalized to the same
value by the programmer, e.g., float(3)+4.5 rather than just 3+4.5.
complex number
An extension of the familiar real number system in which all numbers are
expressed as a sum of a real part and an imaginary part. Imaginary numbers
are real multiples of the imaginary unit (the square root of -1), often written i
in mathematics or j in engineering. Python has builtin support for complex
numbers, which are written with this latter notation; the imaginary part is
written with a j sux, e.g., 3+1j. To get access to complex equivalents of the
math module, use cmath. Use of complex numbers is a fairly advanced
mathematical feature. If you're not aware of a need for them, it's almost certain
you can safely ignore them.
1 of 6
08/31/2011 10:59 AM
D. Glossary
http://www.vithon.org/tutorial/2.5/node18.html
descriptor
Any new-style object that denes the methods __get__(), __set__(), or
__delete__(). When a class attribute is a descriptor, its special binding
behavior is triggered upon attribute lookup. Normally, writing a.b looks up the
object b in the class dictionary for a, but if b is a descriptor, the dened method
gets called. Understanding descriptors is a key to a deep understanding of
Python because they are the basis for many features including functions,
methods, properties, class methods, static methods, and reference to super
classes.
dictionary
An associative array, where arbitrary keys are mapped to values. The use of
dict much resembles that for list, but the keys can be any object with a
__hash__() function, not just integers starting from zero. Called a hash in Perl.
duck-typing
Pythonic programming style that determines an object's type by inspection of
its method or attribute signature rather than by explicit relationship to some
type object ("If it looks like a duck and quacks like a duck, it must be a duck.")
By emphasizing interfaces rather than specic types, well-designed code
improves its exibility by allowing polymorphic substitution. Duck-typing avoids
tests using type() or isinstance(). Instead, it typically employs hasattr()
tests or EAFP programming.
EAFP
Easier to ask for forgiveness than permission. This common Python coding style
assumes the existence of valid keys or attributes and catches exceptions if the
assumption proves false. This clean and fast style is characterized by the
presence of many try and except statements. The technique contrasts with the
LBYL style that is common in many other languages such as C.
__future__
A pseudo module which programmers can use to enable new language features
which are not compatible with the current interpreter. For example, the
expression 11/4 currently evaluates to 2. If the module in which it is executed
had enabled true division by executing:
from __future__ import division
generator
A function that returns an iterator. It looks like a normal function except that
values are returned to the caller using a yield statement instead of a return
statement. Generator functions often contain one or more for or while loops
that yield elements back to the caller. The function execution is stopped at the
yield keyword (returning the result) and is resumed there when the next
2 of 6
08/31/2011 10:59 AM
D. Glossary
http://www.vithon.org/tutorial/2.5/node18.html
GIL
3 of 6
08/31/2011 10:59 AM
D. Glossary
http://www.vithon.org/tutorial/2.5/node18.html
interpreted
Python is an interpreted language, as opposed to a compiled one. This means
that the source les can be run directly without rst creating an executable
which is then run. Interpreted languages typically have a shorter
development/debug cycle than compiled ones, though their programs generally
also run more slowly. See also interactive.
iterable
A container object capable of returning its members one at a time. Examples of
iterables include all sequence types (such as list, str, and tuple) and some
non-sequence types like dict and file and objects of any classes you dene
with an __iter__() or __getitem__() method. Iterables can be used in a for
loop and in many other places where a sequence is needed (zip(), map(), ...).
When an iterable object is passed as an argument to the builtin function
iter(), it returns an iterator for the object. This iterator is good for one pass
over the set of values. When using iterables, it is usually not necessary to call
iter() or deal with iterator objects yourself. The for statement does that
automatically for you, creating a temporary unnamed variable to hold the
iterator for the duration of the loop. See also iterator, sequence, and generator.
iterator
An object representing a stream of data. Repeated calls to the iterator's next()
method return successive items in the stream. When no more data is available
a StopIteration exception is raised instead. At this point, the iterator object is
exhausted and any further calls to its next() method just raise StopIteration
again. Iterators are required to have an __iter__() method that returns the
iterator object itself so every iterator is also iterable and may be used in most
places where other iterables are accepted. One notable exception is code that
attempts multiple iteration passes. A container object (such as a list)
produces a fresh new iterator each time you pass it to the iter() function or
use it in a for loop. Attempting this with an iterator will just return the same
exhausted iterator object used in the previous iteration pass, making it appear
like an empty container.
LBYL
Look before you leap. This coding style explicitly tests for pre-conditions before
making calls or lookups. This style contrasts with the EAFP approach and is
characterized by the presence of many if statements.
list comprehension
A compact way to process all or a subset of elements in a sequence and return
a list with the results. result = ["0x%02x" % x for x in range(256) if x
% 2 == 0] generates a list of strings containing hex numbers (0x..) that are
even and in the range from 0 to 255. The if clause is optional. If omitted, all
elements in range(256) are processed.
mapping
A container object (such as dict) that supports arbitrary key lookups using the
special method __getitem__().
metaclass
The class of a class. Class denitions create a class name, a class dictionary,
4 of 6
08/31/2011 10:59 AM
D. Glossary
http://www.vithon.org/tutorial/2.5/node18.html
and a list of base classes. The metaclass is responsible for taking those three
arguments and creating the class. Most object oriented programming
languages provide a default implementation. What makes Python special is that
it is possible to create custom metaclasses. Most users never need this tool, but
when the need arises, metaclasses can provide powerful, elegant solutions.
They have been used for logging attribute access, adding thread-safety,
tracking object creation, implementing singletons, and many other tasks.
mutable
Mutable objects can change their value but keep their id(). See also
immutable.
namespace
The place where a variable is stored. Namespaces are implemented as
dictionaries. There are the local, global and builtin namespaces as well as
nested namespaces in objects (in methods). Namespaces support modularity by
preventing naming conicts. For instance, the functions __builtin__.open()
and os.open() are distinguished by their namespaces. Namespaces also aid
readability and maintainability by making it clear which module implements a
function. For instance, writing random.seed() or itertools.izip() makes it
clear that those functions are implemented by the random and itertools
modules respectively.
nested scope
The ability to refer to a variable in an enclosing denition. For instance, a
function dened inside another function can refer to variables in the outer
function. Note that nested scopes work only for reference and not for
assignment which will always write to the innermost scope. In contrast, local
variables both read and write in the innermost scope. Likewise, global variables
read and write to the global namespace.
new-style class
Any class that inherits from object. This includes all built-in types like list
and dict. Only new-style classes can use Python's newer, versatile features like
__slots__, descriptors, properties, __getattribute__(), class methods, and
static methods.
Python3000
A mythical python release, not required to be backward compatible, with
telepathic interface.
__slots__
A declaration inside a new-style class that saves memory by pre-declaring
space for instance attributes and eliminating instance dictionaries. Though
popular, the technique is somewhat tricky to get right and is best reserved for
rare cases where there are large numbers of instances in a memory-critical
application.
sequence
An iterable which supports ecient element access using integer indices via
the __getitem__() and __len__() special methods. Some built-in sequence
types are list, str, tuple, and unicode. Note that dict also supports
__getitem__() and __len__(), but is considered a mapping rather than a
5 of 6
08/31/2011 10:59 AM
D. Glossary
http://www.vithon.org/tutorial/2.5/node18.html
sequence because the lookups use arbitrary immutable keys rather than
integers.
Zen of Python
Listing of Python design principles and philosophies that are helpful in
understanding and using the language. The listing can be found by typing
``import this'' at the interactive prompt.
Release 2.5, documentation updated on 19th September, 2006.
See About this document... for information on suggesting changes.
6 of 6
08/31/2011 10:59 AM