You are on page 1of 122

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
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.
Bi ch dn Python http://www.vithon.org/tutorial/2.5/tut.html
1 of 1 08/31/2011 03:19 PM
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
Li ta http://www.vithon.org/tutorial/2.5/node1.html
1 of 2 08/31/2011 03:24 PM
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.
Li ta http://www.vithon.org/tutorial/2.5/node1.html
2 of 2 08/31/2011 03:24 PM
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
Mc lc http://www.vithon.org/tutorial/2.5/node2.html
1 of 3 08/31/2011 03:20 PM
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
Mc lc http://www.vithon.org/tutorial/2.5/node2.html
2 of 3 08/31/2011 03:20 PM
10.3 Thng s dng lnh
10.4 Chuyn hng lung ra v kt thc chng trnh
10.5 Khp mu chui
10.6 Ton hc
10.7 Truy cp internet
10.8 Ngy v gi
10.9 Nn d liu
10.10 o lng hiu sut
10.11 Qun l cht lng
10.12 Km c pin
11. Gii thiu s v b th vin chun - Phn II
11.1 nh dng ra
11.2 To mu
11.3 Lm vic vi bn ghi d liu nh phn
11.4 a lung
11.5 Nht k
11.6 Tham chiu yu
11.7 Cng c lm vic vi danh sch
11.8 S hc du chm ng thp phn
12. Tip theo?
A. Son tho tng tc v Thay th theo lch s
A.1 Son tho dng
A.2 Thay th theo lch s
A.3 Phm nng
A.4 Ch thch
B. S hc du chm ng: Vn v Gii hn
B.1 Li biu din
C. Lch s v Giy php
C.1 Lch s ca phn mm
C.2 iu khon truy cp hoc s dng Python
C.3 Giy php v cng nhn nhng phn mm km theo
C.3.1 Mersenne Twister
C.3.2 Sockets
C.3.3 iu khin bit l du chm ng
C.3.4 Thut ton hm bm MD5
C.3.5 Dch v socket khng ng nht
C.3.6 Qun l cookie
C.3.7 Proling
C.3.8 Theo di hot ng
C.3.9 Chc nng UUencode v UUdecode
C.3.10 Gi th tc xa qua XML
D. Thut ng
Ch mc
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.
Mc lc http://www.vithon.org/tutorial/2.5/node2.html
3 of 3 08/31/2011 03:20 PM
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. Khai v http://www.vithon.org/tutorial/2.5/node3.html
1 of 2 08/31/2011 07:36 AM
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.
1. Khai v http://www.vithon.org/tutorial/2.5/node3.html
2 of 2 08/31/2011 07:36 AM
Bi ch dn Python
2. S dng trnh thng dch Python
2.1 Chy trnh thng dch
B thng dch Python thng c ci t l /usr/local/bin/python trn cc
my tnh ci t sn; b sung /usr/local/bin vo ng dn tm kim ca v
(shell) UNIX s gip khi ng n t mi ni bng mt lnh n gin
python
trong v. V ni m trnh thng dch c ci t l mt ty chn nn khi ci
t trnh thng dch c th s c t mt ni khc; hy hi qun tr h
thng ca bn. (v d /usr/local/python cng l mt v tr hay c dng
ci.)
Trn cc my tnh dng Windows, Python thng c ci t vo
C:\Python24, d vy bn vn c th thay i v tr ci t khi chy chng
trnh ci t. b sung th mc ny vo ng dn, bn c th g lnh sau
ln du nhc lnh trong ca s DOS:
set path=%path%;C:\python24
G mt k t kt thc tp tin (end-of-le character) (Control-D trn UNIX,
Control-Z trn Windows) ti du nhc ca b thng dch s thot khi b thng
dch v tr v trng thi kt thc chng trnh l 0 (khng) cho h iu hnh,
bn cng c th thot khi b thng dch bng cc lnh sau: "import sys;
sys.exit()".
Tnh nng son tho theo dng ca b thng dch thng khng phc tp
lm. Trn UNIX, bt c ai ci t b thng dch u c th bt ch h tr
cho th vin GNU readline, iu ny s b sung tnh nng son tho tng tc
tt hn cng nh cc tnh nng lch s lnh. C th kim tra vic h tr tnh
nng son tho dng bng cch nhn Control-P ti du nhc u tin ca
Python. Nu c ting bp, b thng dch ca bn c h tr son tho dng;
xem ph lc A bit v cc phm. Nu khng c g xy ra, hoc k t P hin
ln, th tnh nng son tho dng khng c h tr; bn ch vic dng phm
li (backspace) xa k t hin ra.
B thng dch Python hot ng kh ging vi v UNIX : khi c gi vi mt
u nhp chun kt ni vi mt thit b u cui (tty device), n c v thc
hin cc lnh mt cch tng tc; khi c gi vi tham s l mt tn tp tin
hoc vi u vo chun l mt tp tin, n c v thc hin kch bn cha trong
tp .
2. S dng trnh thng dch Python http://www.vithon.org/tutorial/2.5/node4.html
1 of 5 08/31/2011 07:37 AM
Mt cch na khi ng b thng dch l lnh "python -c command [arg]
...", s thc thi mt hoc nhiu cu lnh trong command, ging nh ty chn
-c ca v. V cc cu lnh ca Python thng cha cc khong trng hoc cc
k t c bit, chn la an ton nht l bao command bng du nhy kp (").
Mt s m-un cng c th c dng nh kch bn. Chng c th c gi
bng cch s dng c php "python -m module [arg] ...", lnh ny s thc
hin tp tin ngun module nh khi bn ch ra tn tp tin v ng dn y
trn dng lnh.
Xin lu rng c s khc bit gia "python file" v "python <file". Trong
trng hp sau, cc yu cu vo (input request) t chng trnh, v d nh li
gi ti input() v raw_input(), c cung cp t le. V tp tin ny c
c n cui bi trnh phn tch (parser) trc khi chng trnh thc thi,
chng trnh s gp phi cui tp tin (end-of-le) ngay lp tc. Trong trng
hp u (l cch bn s hay dng) cc yu cu vo c cung cp t bt k tp
tin hoc thit b no c kt ni vo u vo chun ca trnh thng dch
Python.
Khi tp tin kch bn (script le) c s dng, i khi s rt hu dng nu c
th chy chng trnh v chuyn sang ch tng tc ngay sau . iu ny
thc hin c bng cch truyn -i trc script (python -i script).
(Phng php ny khng hot ng nu chng trnh c c t u vo
chun, l do ca chuyn ny c gii thch trong on trc.)
2.1.1 Truyn thng s
B thng dch nhn bit tn chng trnh v cc tham s khc c truyn
vo chng trnh trong bin sys.argv, di dng mt danh sch cc chui.
di ti thiu l mt; khi khng c kch bn hoc thng s truyn vo,
sys.argv[0] l mt chui rng. Khi tn kch bn c truyn vo l '-' (c
ngha l u vo chun), sys.argv[0] c gn thnh '-'. Khi -c command
c s dng, sys.argv[0] c gn thnh '-c'. Khi -m module c s dng,
sys.argv[0] c gn l tn y ca m-un np. Cc ty chn sau -c
command hoc -m module khng c s dng bi trnh thng dch Python m
truyn vo sys.argv cho command hay module x l.
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. S dng trnh thng dch Python http://www.vithon.org/tutorial/2.5/node4.html
2 of 5 08/31/2011 07:37 AM
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
>>>
Cc dng ni tip c dng khi nhp vo cc cu trc nhiu dng. Hy xem
v d di, ch cu lnh if :
>>> 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 Trnh thng dch v mi trng ca
n
2.2.1 X l li
Khi xy ra mt li, b dch in ra thng bo li v ln ngc ngn xp (stack
trace). Trong ch tng tc, n s tr li du nhc chnh; khi u vo l
mt tp tin, n s thot vi m li khc 0 sau khi in ra ln ngc ngn xp.
(Cc bit l c x l bi v except trong mt cu lnh try khng phi l cc
li chng ta ni n y.) Mt s li l nghim trng khng iu kin v gy
ra li thot vi gi tr li khc 0; iu ny p dng cho cc trng hp mu
thun ni ti v mt vi trng hp trn b nh. Tt c cc thng bo li u
c xut ra dng xut li chun (standard error stream); kt xut bnh thng
s c xut ra dng xut chun (standard output - xin c hiu l mn hnh,
tp tin...).
G k t ngt (thng l Control-C hoc DEL) vo du nhc chnh hoc du
nhc th s b nhng g nhp vo v tr v du nhc chnh.
2.1
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 .
2.2.2 Cc kch bn Python kh thi
Trn cc h thng UNIX h BSD, cc kch bn Python c th c thc thi trc
tip, nh cc kch bn v (shell script), bng cch thm dng
#! /usr/bin/env python
(gi s rng b thng dch c trong PATH ca ngi dng) u kch bn
v c thuc tnh thc thi (executable mode) cho tp tin . K hiu "#!" phi
l hai k t u tin ca tp tin. Trn cc nn khc, dng u tin ny phi kt
thc bng mt k t xung dng kiu UNIX ("\n"), khng phi Mac OS ("\r")
2. S dng trnh thng dch Python http://www.vithon.org/tutorial/2.5/node4.html
3 of 5 08/31/2011 07:37 AM
hay Windows ("\r\n"). Lu rng du thng "#", c dng bt u mt
ch thch trong Python.
Kch bn c th c t quyn thc thi bng cch dng lnh chmod :
$ chmod +x myscript.py
2.2.3 Bng m m ngun
C th s dng cc bng m khc bng ASCII trong cc tp tin ngun Python.
Cch tt nht l thm cc dng ch thch c bit vo ngay sau dng #!
nh ngha bng m trong tp tin:
# -*- coding: encoding -*-

Vi khai bo ny, mi k t trong tp tin ngun s c xem nh t bng m
encoding, v v vy ta c th vit cc chui Unicode trc tip trong bng m .
Danh sch cc bng m c th c tm thy Tham kho th vin Python,
trong phn codecs.
V d, vit k t biu din ng Euro, ta c th s dng bng m
ISO-8859-15, k hiu Euro c s th t 164 trong bng m. on chng trnh
sau s in ra gi tr 8364 (m Unicode tng ng vi k t biu din Euro) v
thot:
# -*- coding: iso-8859-15 -*-

currency = u""
print ord(currency)

Nu b son tho ca bn h tr lu tp tin theo UTF-8 vi nh du th t
byte UTF-8 (UTF-8 byte order mark - BOM), bn c th dng n thay th cho
mt khai bo bng m. IDLE h tr s tng thch ny nu Options/General
/Default Source Encoding/UTF-8 c thit lp. Ch rng k hiu ny
khng c cc phin bn Python 2.2 tr v trc nhn bit, v cng khng
c h iu hnh nhn bit l cc tp tin kch bn vi cc dng #! (ch c
dng trn cc h UNIX ).
Vi vic s dng UTF-8 (thng qua k hiu cng nh khai bo bng m), cc
k t trong hu ht cc ngn ng trn th gii c th c s dng ng thi
trong cc chui nguyn bn v cc ch thch. S dng cc k t phi chun
ASCII trong cc nh danh th khng c h tr. hin th ng cc k t,
b son tho ca bn nht thit phi nhn bit tp tin UTF-8 v buc phi s
dng cc phng ch h tr tt cc k t ny.
2. S dng trnh thng dch Python http://www.vithon.org/tutorial/2.5/node4.html
4 of 5 08/31/2011 07:37 AM
2.2.4 Tp tin khi to tng tc
Khi bn s dng Python ch tng tc, s rt tin li khi c mt s lnh
chun lun c thc hin mi khi b thng dch khi ng. Bn c th thc
hin vic ny bng cch thit lp mt bin mi trng c tn
PYTHONSTARTUP vi gi tr l tn ca tp tin bn cha cc cu lnh khi
to. Cch ny tng t nh chc nng .prole ca v UNIX .
Tp tin ny ch c c trong phin lm vic tng tc, khng c tc dng
vi cc kch bn, v khi /dev/tty c ch nh r l ngun lnh (nu khng th
trng hp ny cng ging nh mt phin lm vic tng tc). N c thc
thi trong cng vng tn (namespace) m cc lnh tng tc c thc thi,
cho nn cc i tng n nh ngha, hoc nhp vo (import) c th c
dng m khng cn xc nhn trong phin lm vic tng tc. Bn cng c th
thay i du nhc sys.ps1 v sys.ps2 trong tp tin ny.
Nu bn mun c cc tp khi ng b sung t th mc hin ti, bn c th
lp trnh iu ny trong tp tin khi ng vi m nh "if
os.path.isfile('.pythonrc.py'): execfile('.pythonrc.py')". Nu bn
mun dng tp tin khi ng trong mt kch bn, bn phi ch r iu ny
trong kch bn:
import os
filename = os.environ.get('PYTHONSTARTUP')
if filename and os.path.isfile(filename):
execfile(filename)
Ghi ch
... du nhc chnh.
2.1
Gi GNU Readline c mt li c th ngn cn iu 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. S dng trnh thng dch Python http://www.vithon.org/tutorial/2.5/node4.html
5 of 5 08/31/2011 07:37 AM
Bi ch dn Python
3. Gii thiu s v Python
Trong v d say, u vo v u ra c phn bit bng s hin din ca du
nhc (">>> " v "... "): lp li v t, bn cn nhp vo mi th sau du
nhc, khi du nhc xut hin; cc dng khng bt u bng mt du nhc l kt
qu xut t trnh thng dch. Lu rng du nhc th (secondary prompt) trn
mt dng ring n c ngha l bn phi nhn mt dng trng; dng ny dng
kt thc mt lnh nhiu dng.
Nhiu v d trong ti liu ny, ngay c nhng v d nhp t dng lnh tng
tc, c c ch thch. Cc ch thch trong Python bt u bng mt du thng,
"#", v ko di ti ht dng. Mt ch thch c th xut hin u dng, hoc
theo sau khong trng hoc m, nhng khng phi trong mt chui. Mt du
thng trong mt chui ch l mt du thng.
Mt vi v d:
# this is the first comment
SPAM = 1 # and this is the second comment
# ... and now a third!
STRING = "# This is not a comment."
3.1 Dng Python nh l my tnh
Hy th mt vi lnh Python n gin. Khi ng trnh thng dch v ch du
nhc chnh, ">>> ". (Khng lu u.)
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:
>>> 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:
3. Gii thiu s v Python http://www.vithon.org/tutorial/2.5/node5.html
1 of 12 08/31/2011 07:38 AM
... 7/3
2
>>> 7/-3
-3
Du bng ("=") c dng gn mt gi tr vo mt bin. Sau , khng c gi
tr no c hin ra trc du nhc tng tc k:
>>> width = 20
>>> height = 5*9
>>> width * height
900
Mt gi tr c th c gn vo nhiu bin cng mt lc:
>>> x = y = z = 0 # Zero x, y and z
>>> x
0
>>> y
0
>>> z
0
Python hon ton h tr du chm ng; cc ton t vi cc ton hng khc
kiu chuyn ton hng s nguyn thnh du chm ng:
>>> 3 * 3.75 / 1.5
7.5
>>> 7.0 / 2
3.5
S phc cng c h tr; s o c vit vi hu t "j" hoc "J". Cc s phc
vi phn thc khc khng c vit "(real+imagj)", hoc c th c to ra vi
hm "complex(real, imag)".
>>> 1j * 1J
(-1+0j)
>>> 1j * complex(0,1)
(-1+0j)
>>> 3+1j*3
(3+3j)
>>> (3+1j)*3
(9+3j)
>>> (1+2j)/(1+1j)
(1.5+0.5j)
Cc s phc lun c th hin bi hai s chm ng, phn thc v phn o.
ly cc phn t mt s phc z, dng z.real v z.imag.
>>> a=1.5+0.5j
>>> a.real
3. Gii thiu s v Python http://www.vithon.org/tutorial/2.5/node5.html
2 of 12 08/31/2011 07:38 AM
1.5
>>> a.imag
0.5
Cc hm chuyn i t chm ng sang s nguyn (float(), int() v long())
khng dng c vi s phc -- khng c mt cch chnh xc no chuyn i
mt s phc thnh mt s thc. Dng abs(z) ly ln (magnitude) (nh l
mt s chm ng) hoc z.real ly phn thc.
>>> a=3.0+4.0j
>>> float(a)
Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: can't convert complex to float; use abs(z)
>>> a.real
3.0
>>> a.imag
4.0
>>> abs(a) # sqrt(a.real**2 + a.imag**2)
5.0
>>>
Trong ch tng tc, biu thc c in ra cui cng c gn vo bin _. Khi
bn dng Python nh l my tnh, n s gip bn tip tc cc php tnh d hn,
v d:
>>> tax = 12.5 / 100
>>> price = 100.50
>>> price * tax
12.5625
>>> price + _
113.0625
>>> round(_, 2)
113.06
>>>
Bin ny nn c coi l ch c t pha ngi dng. Khng nn gn mt gi tr
vo bin ny trc tip -- bn s to mt bin cc b ring vi cng tn, che i
bin c sn vi cch thc (behavior) diu k ca n.
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. Gii thiu s v Python http://www.vithon.org/tutorial/2.5/node5.html
3 of 12 08/31/2011 07:38 AM
"doesn't"
>>> '"Yes," he said.'
'"Yes," he said.'
>>> "\"Yes,\" he said."
'"Yes," he said.'
>>> '"Isn\'t," she said.'
'"Isn\'t," she said.'
Cc chui c th ph nhiu dng theo nhiu cch. Cc dng tip tc
(continuation line) c th c dng, vi mt du sut huyn l k t cui cng
trn mt dng cho bit rng dng k l s ni tip ca dng ny:
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."
print hello
Lu rng cc dng mi vn cn c chn trong chui vi \n; k t dng mi
theo sau du sut huyn s b b qua. V d ny s in ra:
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.
Tuy nhin, nu ta lm cho chui trc tip thnh chui ``th'', cc dy \n s
khng c chuyn thnh cc dng mi, nhng du sut huyn cui dng, v
k t dng mi trong ngun, s u c thm vo trong chui nh d liu. Cho
nn, v d:
hello = r"This is a rather long string containing\n\
several lines of text much as you would do in C."
print hello
s in:
This is a rather long string containing\n\
several lines of text much as you would do in C.
Hoc, cc chui c th c vy quanh trong mt cp nhy ba: """ hoc '''.
Cui mi dng khng cn thm du sut huyn khi dng nhy ba, v chng s
c mt trong chui.
print """
Usage: thingy [OPTIONS]
-h Display this usage message
-H hostname Hostname to connect to
"""
xut ra:
3. Gii thiu s v Python http://www.vithon.org/tutorial/2.5/node5.html
4 of 12 08/31/2011 07:38 AM
Usage: thingy [OPTIONS]
-h Display this usage message
-H hostname Hostname to connect to
Trnh thng dch in ra kt qu ca cc tc v chui theo cng cch nh khi
chng c nhp vo: trong du nhy, v vi cc k t du nhy hay c bit
khc c thot ngha (escape) bng du sut huyn, hin gi tr thc. Chui
c km trong du nhy i nu chui cha mt du nhy n v khng cha
du nhy i, ngoi ra n s c cha trong cc du nhy n. (Cu lnh
print , c gii thch sau, c th dng vit cc chui khng c du nhy
hoc thot ngha.)
Cc chui c th c ni vi nhau vi ton t + , v c lp li vi *:
>>> word = 'Help' + 'A'
>>> word
'HelpA'
>>> '<' + word*5 + '>'
'<HelpAHelpAHelpAHelpAHelpA>'
Hai chui trc tip k nhau c t ng ni vi nhau; dng u tin bn trn
c th c bit "word = 'Help' 'A'"; vic ny ch c tc dng vi hai chui
trc tip (string literal), khng c tc dng vi cc biu thc chui bt k khc:
>>> 'str' 'ing' # <- This is ok
'string'
>>> 'str'.strip() + 'ing' # <- This is ok
'string'
>>> 'str'.strip() 'ing' # <- This is invalid
File "<stdin>", line 1, in ?
'str'.strip() 'ing'
^
SyntaxError: invalid syntax
Cc chui c th c ch mc (subscript hoc index); nh trong C, k t u
tin ca mt chui c ch mc 0. Khng c kiu k t ring; mt k t ch n
gin l mt chui c di l mt. Nh trong Icon, chui con c th c ch
nh theo cch vit ct lt (slice notation): hai ch mc phn cch bi mt du
hai chm.
>>> word[4]
'A'
>>> word[0:2]
'He'
>>> word[2:4]
'lp'
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.
3. Gii thiu s v Python http://www.vithon.org/tutorial/2.5/node5.html
5 of 12 08/31/2011 07:38 AM
>>> word[:2] # The first two characters
'He'
>>> word[2:] # Everything except the first two characters
'lpA'
Khng nh C, cc chui Python khng th b thay i. Php gn vo mt v tr
ch mc trong mt chui s gy ra li:
>>> word[0] = 'x'
Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: object doesn't support item assignment
>>> word[:1] = 'Splat'
Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: object doesn't support slice assignment
Tuy nhin, vic to mt chui vi ni dung gp chung cng d v hiu qu:
>>> 'x' + word[1:]
'xelpA'
>>> 'Splat' + word[4]
'SplatA'
y l mt tnh cht bt bin hu dng khc ca tc v ct lt: s[:i] + s[i:]
bng s.
>>> word[:2] + word[2:]
'HelpA'
>>> word[:3] + word[3:]
'HelpA'
Cc ch mc ct lt gim sinh (degenerate) c x l rt kho: mt ch mc
qu ln s c thay bng kch thc chui, mt gii hn trn nh hn gii hn
di tr v mt chui rng.
>>> word[1:100]
'elpA'
>>> word[10:]
''
>>> word[2:1]
''
Cc ch mc c th l s m, bt u m t bn phi. V d:
>>> word[-1] # The last character
'A'
>>> word[-2] # The last-but-one character
'p'
>>> word[-2:] # The last two characters
'pA'
>>> word[:-2] # Everything except the last two characters
3. Gii thiu s v Python http://www.vithon.org/tutorial/2.5/node5.html
6 of 12 08/31/2011 07:38 AM
'Hel'
Nhng lu rng -0 tht ra cng l 0, cho nn n khng bt u m t bn
phi!
>>> word[-0] # (since -0 equals 0)
'H'
Cc ch mc ct lt m ngoi phm vi th b thu ngn, nhng ng th kiu ny
vi cc ch mc mt phn t (khng phi ct lt):
>>> word[-100:]
'HelpA'
>>> word[-10] # error
Traceback (most recent call last):
File "<stdin>", line 1, in ?
IndexError: string index out of range
Cch tt nht nh hot ng ca ct lt l ngh v cc ch mc nh ang tr
vo gia cc k t, vi cnh tri ca k t u tin l 0. Sau cnh phi ca
k t cui cng ca mt chui ca n k t c ch mc n, v d:
+---+---+---+---+---+
| H | e | l | p | A |
+---+---+---+---+---+
0 1 2 3 4 5
-5 -4 -3 -2 -1
Cc s hng u cho bit v tr ca cc ch mc 0...5 trong chui; dng th hai
cho bit cc ch mc m tng ng. Mt lt t i ti j cha ton b cc k t gia
cc cnh nh s i v jtng ng.
Vi cc ch mc khng m, chiu di ca lt l hiu ca cc ch mc, nu c hai
u trong gii hn. V d, di ca word[1:3] l 2.
Hm c sn len() tr v di ca mt chui:
>>> s = 'supercalifragilisticexpialidocious'
>>> len(s)
34
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.
3. Gii thiu s v Python http://www.vithon.org/tutorial/2.5/node5.html
7 of 12 08/31/2011 07:38 AM
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.
3.1.3 Chui Unicode
Bt u vi Python 2.0, mt kiu d liu mi cha d liu vn bn c cung
cp cho nh lp trnh: i tng Unicode. N c th c dng cha v thay
i d liu Unicode (xem http://www.unicode.org/) v tch hp tt vi cc i
tng chui c, bng vic t chuyn i khi cn.
Unicode c li im l cung cp mt s th t (ordinal) cho mi k t trong cc
bn tho dng trong cc vn bn xa v nay. Trc kia, ch c 256 s th t
cho cc k t bn tho. Cc vn bn xa b gii hn vo mt trang m (code
page) dng nh x cc s vo cc k t bn tho. iu ny dn n nhiu ln
ln c bit l trong ng cnh quc t ha (internationalization, hay c vit
tt l "i18n" -- "i" + 18 k t + "n") phn mm. Unicode gii quyt cc vn
ny bng cc nh ngha mt trang m cho mi bn tho.
To mt chui Unicode trong Python d nh to mt chui thng:
>>> u'Hello World !'
u'Hello World !'
K t "u" ng trc du nhy cho bit y l mt chui Unicode cn c to.
Nu bn mun thm cc k t c bit trong chui, bn c th lm vy bng
cch vit thot ngha Unicode-Escape ca Python. V d:
>>> u'Hello\u0020World !'
u'Hello World !'
Dy thot ngha \u0020 cho bit chn mt k t Unicode vi th t 0x0020 (k
t khong trng) vo mt v tr nh.
Cc k t khc c thng dch theo th t tng ng ca chng nh l th t
Unicode. Nu bn c cc chui trc tip trong bng m Latin-1 chun c
dng nhiu nc phng Ty, bn s thy rng 256 k t u ca bng m
Unicode ging nh 256 k t ca Latin-1.
Cho cc chuyn gia, Python cng h tr cc chui Unicode th. Bn phi dng
tin t 'ur' bo Python dng bng m thot-ngha-Unicode-th
(Raw-Unicode-Escape) . N s ch p dng php chuyn i \uXXXX bn trn
nu c mt s l cc du sut huyn pha trc k t 'u' nh.
>>> ur'Hello\u0020World !'
u'Hello World !'
>>> ur'Hello\\u0020World !'
u'Hello\\\\u0020World !'
3. Gii thiu s v Python http://www.vithon.org/tutorial/2.5/node5.html
8 of 12 08/31/2011 07:38 AM
Ch th s hu dng trong trng hp bn phi nhp tht nhiu du sut
huyn, nh khi bn dng trong cc biu thc chnh quy (regular expression).
Ngoi nhng bng m chun ny, Python cung cp mt tp hp cc cch khc
to cc chui Unicode t mt bng m bit.
Hm c sn unicode() cung cp truy cp vo tt c b m/gii m (codec -
COder and DECoder) Unicode ng k. Mt vi bng m ph thng m cc
b chuyn m ny c th chuyn gm Latin-1, ASCII, UTF-8, v UTF-16. Hai
bng m sau cng l cc bng m c kch thc thay i v cha mi k t
Unicode trong mt hoc nhiu byte. Bng m mc nh thng c thit lp l
ASCII, n cho php cc k t t 0 ti 127 v cm cc k t khc. Khi mt chui
Unicode c in, vit vo tp tin, hoc chuyn vi str(), s chuyn i din ra
vi bng m mc nh ny.
>>> 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: ordinal not in
chuyn mt chui Unicode thnh mt chui 8-bit bng mt bng m no ,
cc i tng Unicode cung cp mt phng thc encode() nhn mt thng s,
tn ca bng m. Bn nn dng tn bng m vit thng.
>>> u"".encode('utf-8')
'\xc3\xa4\xc3\xb6\xc3\xbc'
Nu bn c d liu trong mt bng m no v mun to ra mt chui
Unicode tng ng t n, bn c th dng hm unicode() vi tn bng m l
thng s th hai.
>>> unicode('\xc3\xa4\xc3\xb6\xc3\xbc', 'utf-8')
u'\xe4\xf6\xfc'
3.1.4 Danh sch
Python bit mt s kiu d liu gp (compound) , dng nhm cc gi tr vi
nhau. Kiu linh hot nht l danh sch (list), c th c vit nh l mt danh
sch cc gi tr phn cch bi du phy gia ngoc vung.
>>> a = ['spam', 'eggs', 100, 1234]
>>> a
['spam', 'eggs', 100, 1234]
3. Gii thiu s v Python http://www.vithon.org/tutorial/2.5/node5.html
9 of 12 08/31/2011 07:38 AM
Cng nh cc ch mc chui, ch mc danh sch bt u t 0, v danh sch c
th c ct lt, gm v vn vn:
>>> a[0]
'spam'
>>> a[3]
1234
>>> a[-2]
100
>>> a[1:-1]
['eggs', 100]
>>> a[:2] + ['bacon', 2*2]
['spam', 'eggs', 'bacon', 4]
>>> 3*a[:3] + ['Boo!']
['spam', 'eggs', 100, 'spam', 'eggs', 100, 'spam', 'eggs', 100, 'Boo!']
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]
Gn vo cc ct lt cng c th lm c, v n c th thay i kch thc ca
danh sch hoc xa sch n.
>>> # Replace some items:
... a[0:2] = [1, 12]
>>> a
[1, 12, 123, 1234]
>>> # Remove some:
... a[0:2] = []
>>> a
[123, 1234]
>>> # Insert some:
... a[1:1] = ['bletch', 'xyzzy']
>>> a
[123, 'bletch', 'xyzzy', 1234]
>>> # Insert (a copy of) itself at the beginning
>>> a[:0] = a
>>> a
[123, 'bletch', 'xyzzy', 1234, 123, 'bletch', 'xyzzy', 1234]
>>> # Clear the list: replace all items with an empty list
>>> a[:] = []
>>> a
[]
Hm c sn len() cng p dng vo danh sch:
3. Gii thiu s v Python http://www.vithon.org/tutorial/2.5/node5.html
10 of 12 08/31/2011 07:38 AM
>>> len(a)
8
C th lng cc danh sch (to danh sch cha cc danh sch khc), v d:
>>> q = [2, 3]
>>> p = [1, q, 4]
>>> len(p)
3
>>> p[1]
[2, 3]
>>> p[1][0]
2
>>> p[1].append('xtra') # See section 5.1
>>> p
[1, [2, 3, 'xtra'], 4]
>>> q
[2, 3, 'xtra']
Lu trong v d, p[1] v q tht ra ch ti cng i tng! Chng ta s ni v
ngha ca i tng (object semantics) trong cc chng sau.
3.2 Nhng bc u lp trnh
D nhin, chng ta c dng Python cho cc tc v phc tp khc. V d ta c
th vit mt dy con ban u ca dy Fibonacci nh sau:
>>> # 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
V d ny gii thiu mt vi tnh nng mi.
Dng u tin cha mt php gn a bin (multiple assignment): cc bin
a v b ng lot nhn gi tr mi 0 v 1. Trong dng cui n c dng
mt ln na, cho thy rng cc biu thc pha phi c xc nh trc
khi bt k php gn no c thc hin. Cc biu thc pha phi c nh
gi t tri qua phi.
Vng lp while thc thi min l iu kin ( y: b < 10) vn l ng
3. Gii thiu s v Python http://www.vithon.org/tutorial/2.5/node5.html
11 of 12 08/31/2011 07:38 AM
(true). Trong Python, nh C, mi gi tr s nguyn khc khng l ng;
khng l sai (false). iu kin cng c th l danh sch, chui, hoc bt k
kiu dy no; chiu di khc khng l ng, dy rng l sai. Php so snh
dng trong v d l mt php so snh n gin. Cc ton t so sanh chun
c vit nh trong C: < (nh hn), > (ln hn), == (bng), <= (nh hn
hoc bng), >= (ln hn hoc bng) v != (khng bng).
Vng lp Thn vng lp c tht vo: cc thc vo l cch ca Python
nhm cc cu lnh. Python khng (cha) cung cp mt cng c son tho
dng nhp thng minh, cho nn bn phi nhp vo mt tab hoc khong
trng cho mi dng tht vo. Trong thc t, bn s chun b u vo phc
tp hn cho Python vi mt trnh son tho; a s chng u c chc nng
t ng tht vo. Khi mt cu lnh ghp (compound statement) c nhp
vo mt cch tng tc, n phi c theo sau bi mt dng trng ch
ra s kt thc (v b phn tch khng th khi no bn nhp dng cui). Lu
rng mi dng ca mt khi phi c tht vo nh nhau.
Vng lp print (cu lnh) vit ra gi tr ca biu thc n c cung cp.
N khc vi vic ch vit cc biu thc bn mun vit (nh chng ta lm
trong cc v d my tnh trc) trong vic x l nhiu biu thc v chui.
Cc chui c in ra khng c du nhy, v mt khong trng c chn
vo gia cc phn t, bn c th nh dng chng p hn, v d:
>>> i = 256*256
>>> print 'The value of i is', i
The value of i is 65536
Du phy sau cng trnh dng mi sau khi xut:
>>> a, b = 0, 1
>>> while b < 1000:
... print b,
... a, b = b, a+b
...
1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987
Lu rng trnh thng dch chn mt dng mi trc khi n in ra du
nhc k nu dng trc cha xong.
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.
3. Gii thiu s v Python http://www.vithon.org/tutorial/2.5/node5.html
12 of 12 08/31/2011 07:38 AM
Bi ch dn Python
4. Bn thm v lung iu khin
Ngoi cu lnh while va gii thiu, Python c cc cu lnh iu khin lung t cc ngn ng khc, vi
cht sa i.
4.1 if cu lnh
C l loi cu lnh bit n nhiu nht l cu lnh if . V d:
>>> x = int(raw_input("Please enter an integer: "))
>>> if x < 0:
... x = 0
... print 'Negative changed to zero'
... elif x == 0:
... print 'Zero'
... elif x == 1:
... print 'Single'
... else:
... print 'More'
...
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.2 for cu lnh
for trong Python khc mt cht vi C hoc Pascal. Thay v lp qua mt dy s (nh trong Pascal), hoc
cho php ngi dng t nh ngha bc lp v iu kin dng (nh C), cu lnh for ca Python lp
qua cc phn t ca mt dy bt k (mt danh sch, hoc mt chui), theo th t m chng xut hin
trong dy. V d:
>>> # Measure some strings:
... a = ['cat', 'window', 'defenestrate']
>>> for x in a:
... print x, len(x)
...
cat 3
window 6
defenestrate 12
Rt nguy him nu bn sa i dy trong khi bn ang lp qua n. Nu bn cn sa i mt danh sch
khi ang lp (v d nh nhn i cc phn t no ) bn s cn phi lp qua mt bn sao ca n.
Cch vit ct ming lm cho vic ny n gin:
>>> for x in a[:]: # make a slice copy of the entire list
... if len(x) > 6: a.insert(0, x)
...
>>> a
['defenestrate', 'cat', 'window', 'defenestrate']
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]
4. Bn thm v lung iu khin http://www.vithon.org/tutorial/2.5/node6.html
1 of 7 08/31/2011 07:39 AM
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]
lp qua cc ch mc ca mt dy, gp range() v len() nh sau:
>>> a = ['Mary', 'had', 'a', 'little', 'lamb']
>>> for i in range(len(a)):
... print i, a[i]
...
0 Mary
1 had
2 a
3 little
4 lamb
4.4 break v continue cu lnh, v else v lp
break , nh trong C, nhy ra khi phm vng lp for hay while nh nht cha n.
continue , cng c mn t C, tip tc ln lp k ca vng lp.
Cc cu lnh lp c th c v else ; n c thc thi khi vng lp kt thc v danh sch lp cn (vi
for) hoc khi iu kin l sai (vi while), v khng c thc thi khi vng lp kt thc bi cu lnh
break . V d vng lp sau tm cc s nguyn t:
>>> 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
4.5 pass cu lnh
pass khng lm g c. N c th c dng khi c php cn mt cu lnh nhng chng trnh khng
cn tc v no. V d:
>>> while True:
... pass # Busy-wait for keyboard interrupt
...
4.6 nh ngha hm
4. Bn thm v lung iu khin http://www.vithon.org/tutorial/2.5/node6.html
2 of 7 08/31/2011 07:39 AM
Chng ta c th to mt hm in ra dy Fibonacci:
>>> 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)
1 1 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
tham chiu i tng, khng phi l gi tr ca i tng).
4.1
Khi mt hm gi mt hm khc, mt bng
k hiu cc b c to ra cho lnh gi .
Mt nh ngha hm to tn hm trong bng k hiu hin ti. Gi tr ca tn hm c mt kiu c
nhn ra bi trnh thng dch l hm do ngi dng nh ngha. Gi tr ny c th c gn vo mt tn
khc v sau c th c s dng nh mt hm. y l mt cch i tn tng qut:
>>> fib
<function fib at 10042ed0>
>>> f = fib
>>> f(100)
1 1 2 3 5 8 13 21 34 55 89
Bn c th ni rng fib khng phi l mt hm (function) m l mt th tc (procedure). Trong
Python, cng nh C, th tc chng qua l hm khng c gi tr tr v. Tht s, ni r hn mt cht,
th tc cng tr v gi tr mc d l mt gi tr v ngha. Gi tr ny c gi l None (n l mt tn c
sn). In ra gi tr None thng b trnh thng dch b qua nu n l gi tr duy nht c in ra. Bn c
th thy n nu bn mun:
>>> print fib(0)
None
Bn cng c th d dng vit mt hm tr v mt danh sch cc s ca dy Fibonacci thay v in n ra:
>>> 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]
4. Bn thm v lung iu khin http://www.vithon.org/tutorial/2.5/node6.html
3 of 7 08/31/2011 07:39 AM
V d ny cho thy mt vi tnh nng mi ca Python:
return tr v vi mt gi tr t mt hm. return khng c thng s biu thc i km tr v None.
Rt ra khi mt th tc cng tr v Noneca hm.
Cu lnh result.append(b) gi mt phng thc ca i tng danh sch. result. Mt phng
thc l mt hm `thuc v' mt i tng v c tn obj.methodname, vi obj l mt i tng no
(c th l mt biu thc), v methodname l tn ca mt phng thc c nh ngha bi kiu
ca i tng. Cc kiu khc nhau nh ngha cc phng thc khc nhau. Phng thc ca cc
kiu khc nhau c th c cng tn m khng dn n s kh hiu. (Bn c th nh ngha kiu i
tng v phng thc cho ring bn, dng lp, nh s c bn n cc chng sau.) Phng
thc append() dng trong v d ny c nh ngha cho cc i tng danh sch; n thm mt
phn t mi vo cui danh sch. Trong v d ny, n tng ng vi "result = result + [b]",
nhng hiu qu hn.
4.7 Bn thm v nh ngha hm
Bn cng c th nh ngha cc hm vi s lng thng s thay i. C ba dng, v chng c th c
dng chung vi nhau.
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
Hm ny c th c gi nh sau: ask_ok('Do you really want to quit?') hoc nh sau:
ask_ok('OK to overwrite the file?', 2)ca hm.
V d ny gii thiu t kha in . N kim tra xem mt dy c cha mt gi tr no khng.
Cc gi tr mc nh c nh gi ti ni hm c nh ngha trong phm vi nh ngha (dening
scope) , do
i = 5
def f(arg=i):
print arg
i = 6
f()
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. Bn thm v lung iu khin http://www.vithon.org/tutorial/2.5/node6.html
4 of 7 08/31/2011 07:39 AM
S in ra
[1]
[1, 2]
[1, 2, 3]
Nu bn khng mun mc nh c dng chung trong cc li gi sau, bn c th vit mt hm nh th
ny:
def f(a, L=None):
if L is None:
L = []
L.append(a)
return L
4.7.2 Thng s t kha
Cc hm cng c th c gi theo thng s t kha (keyword argument) theo dng "keyword = value".
V d, hm sau:
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, "!"
c th c gi theo bt k cch no:
parrot(1000)
parrot(action = 'VOOOOOM', voltage = 1000000)
parrot('a thousand', state = 'pushing up the daisies')
parrot('a million', 'bereft of life', 'jump')
nhng nhng li gi sau u khng hp l:
parrot() # required argument missing
parrot(voltage=5.0, 'dead') # non-keyword argument following keyword
parrot(110, voltage=220) # duplicate value for argument
parrot(actor='John Cleese') # unknown keyword
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()
4. Bn thm v lung iu khin http://www.vithon.org/tutorial/2.5/node6.html
5 of 7 08/31/2011 07:39 AM
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.
4.7.3 Danh sch thng s bt k
Cui cng, mt la chn t dng nht ch nh rng mt hm c th c gi vi bt k s thng s.
Cc thng s ny s c gi v trong mt b. Trc cc thng s khng xc nh, khng hoc nhiu
hn cc thng s chnh quy c th c mt.
def fprintf(file, format, *args):
file.write(format % args)
4.7.4 Tho danh sch thng s
Trng hp ngc xy ra khi cc thng s nm trong mt danh sch hoc mt b nhng cn c
tho ra cho li gi hm cn nhng thng s v tr ring. V d, hm c sn range() cn nhn cc thng
s ring start v stop . Nu chng khng c cung cp ring l, vit lnh gi hm vi ton t * tho
cc thng s ny ra khi mt danh sch hoc b:
>>> range(3, 6) # normal call with separate arguments
[3, 4, 5]
>>> args = [3, 6]
>>> range(*args) # call with arguments unpacked from a list
[3, 4, 5]
Theo cng mt kiu, t in c th cung cp cc thng s t kha vi ton t **:
>>> def parrot(voltage, state='a stiff', action='voom'):
... print "-- This parrot wouldn't", action,
... print "if you put", voltage, "volts through it.",
... print "E's", state, "!"
...
>>> d = {"voltage": "four million", "state": "bleedin' demised", "action": "VOOM"}
>>> parrot(**d)
-- This parrot wouldn't VOOM if you put four million volts through it. E's bleedin' demised !
4.7.5 Dng lambda
Theo yu cu chung, mt vi tnh nng thng thy trong cc ngn ng lp trnh hm nh Lisp c
thm vo Python. Vi t kha lambda , cc hm v danh (anonymous function) c th c to ra. y
l mt hm tr v tng ca hai thng s: "lambda a, b: a+b". Dng lambda c th c dng bt k
4. Bn thm v lung iu khin http://www.vithon.org/tutorial/2.5/node6.html
6 of 7 08/31/2011 07:39 AM
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:
>>> def make_incrementor(n):
... return lambda x: x + n
...
>>> f = make_incrementor(42)
>>> f(0)
42
>>> f(1)
43
4.7.6 Chui ti liu
C nhng quy lut ang hnh thnh v ni dung v nh dng ca cc chui ti liu.
Dng u tin cn phi lun lun l mt tm tt ngn, xc tch v mc ch ca i tng. d hiu,
n khng nn ch ra c th tn hoc kiu ca i tng v chng c th c hnh thc khc (t khi tn
l mt ng t din t hot ng ca hm). Dng ny cn bt u bng mt ch hoa v kt thc bng
mt du chm.
Nu c nhiu dng trong chui ti liu, dng th hai nn l mt dng trng, r rng phn bit tm tt
v phn cn li. Cc dng sau nn l mt hoc nhiu on hng dn v cch gi, cc hiu ng ph,
v.v...
B phn tch ng php Python khng lc tht hng t cc chui a dng (multi-line string literal) trong
Python, so nn cc cng c x l ti liu cn phi lc tht hng nu cn. Vic ny c lm theo mt
cch chung. Dng khng trng u tin sau dng u tin ca chui xc nh mc tht vo cho ton b
chui ti liu. (Ta khng th dng dng u tin v n thng nm k du nhy u chui cho nn mc
tht vo ca n khng c xc nh trong cch vit chui.) Khong trng ``tng ng'' vi mc tht
vo ny c b khi mi u dng trong chui. Khng nn c cc dng tht vo t hn, nhng nu gp
phi, ton b khong trng u ca chng nn c b i. Tnh tng ng ca khong trng cn
c kim tra sau khi m rng tab (thng thng thnh 8 khong trng).
u l v d ca mt docstring a dng:
>>> 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.
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.
4. Bn thm v lung iu khin http://www.vithon.org/tutorial/2.5/node6.html
7 of 7 08/31/2011 07:39 AM
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.
5.1 Bn thm v danh sch
Kiu d liu danh sch (kiu list) c mt s phng thc khc. y l ton b
cc phng thc ca i tng danh sch:
append(x)
Thm mt phn t vo cui danh sch; tng ng vi a[len(a):] =
[x].
extend(L)
Ni rng danh sch bng cch chn vo tt c cc phn t ca danh sch
ch nh; tng ng vi a[len(a):] = L.
insert(i, x)
Chn mt phn t vo v tr ch nh. Thng s u l ch mc ca phn t
s b y li, cho nn a.insert(0, x) chn vo u danh sch, v
a.insert(len(a), x) tng ng vi a.append(x).
remove(x)
B ra khi danh sch phn t u tin c gi tr l x. S c li nu khng c
phn t nh vy.
pop([i])
B khi danh sch phn t v tr ch nh, v tr v chnh n. Nu khng
ch nh v tr, a.pop() b v tr v phn t cui trong danh sch. (Ngoc
vung xung quanh i trong khai bo hm cho bit thng s l khng bt
buc, khng c ngha l bn cn g du ngoc vung v tr . Bn s
thy cch vit ny thng xuyn trong Tham kho th vin Python.)
index(x)
Tr v ch mc ca phn t trong danh sch m c gi tr l x. S c li nu
khng c phn t nh vy.
count(x)
Tr v s ln x xut hin trong danh sch.
sort()
Sp xp cc phn t trong danh sch, ngay ti ch.
5. Cu trc d liu http://www.vithon.org/tutorial/2.5/node7.html
1 of 11 08/31/2011 07:39 AM
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]
5.1.1 Dng danh sch nh ngn xp
Cc phng thc ca danh sch lm cho n rt d s dng nh l ngn xp
(stack), l ni m phn t cui c thm vo l phn t u c ly ra (``vo
sau, ra trc'' hay ``last-in, rst-out''). thm phn t vo nh ca ngn xp,
dng append(). ly mt phn t t nh ca ngn xp, dng pop() m khng
ch nh ch mc. V d:
>>> stack = [3, 4, 5]
>>> stack.append(6)
>>> stack.append(7)
>>> stack
[3, 4, 5, 6, 7]
>>> stack.pop()
7
>>> stack
[3, 4, 5, 6]
>>> stack.pop()
6
>>> stack.pop()
5
>>> stack
[3, 4]
5.1.2 Dng danh sch nh hng i
5. Cu trc d liu http://www.vithon.org/tutorial/2.5/node7.html
2 of 11 08/31/2011 07:39 AM
Bn cng c th thun tin dng danh sch nh l hng i (queue), ni m
phn t c thm vo u tin l phn t c ly ra u tin (``vo trc, ra
trc'' hay ``rst-in, rst-out''). thm mt phn t vo cui hng i, dng
append(). ly mt phn t t u hng i, dng pop() vi 0 l ch mc. V
d:
>>> queue = ["Eric", "John", "Michael"]
>>> queue.append("Terry") # Terry arrives
>>> queue.append("Graham") # Graham arrives
>>> queue.pop(0)
'Eric'
>>> queue.pop(0)
'John'
>>> queue
['Michael', 'Terry', 'Graham']
5.1.3 Cng c lp trnh hng hm
C sn ba hm rt hu dng khi dng vi danh sch: filter(), map(), v
reduce().
"filter(function, sequence)" tr v mt dy cha cc phn t t dy m
function(item) c gi tr ng. Nu sequence l mt string hoc tuple, th kt qu
tr v s c cng kiu; ngc li, s lun lun l mt list. V d, tm mt vi
s nguyn t:
>>> def f(x): return x % 2 != 0 and x % 3 != 0
...
>>> filter(f, range(2, 25))
[5, 7, 11, 13, 17, 19, 23]
"map(function, sequence)" gi function(item) vi mi phn t trong dy v tr v
mt danh sch cc gi tr tr v. V d, tnh mt vi s lp phng:
>>> def cube(x): return x*x*x
...
>>> map(cube, range(1, 11))
[1, 8, 27, 64, 125, 216, 343, 512, 729, 1000]
C th truyn vo nhiu dy; hm phi nhn tng y thng s vi mi phn t
trong mi dy l mt thng s (hoc None nu dy no ngn hn dy cn
li). V d:
>>> seq = range(8)
>>> def add(x, y): return x+y
...
>>> map(add, seq, seq)
[0, 2, 4, 6, 8, 10, 12, 14]
"reduce(function, sequence)" tr v gi tr duy nht c to ra t vic gi hm
5. Cu trc d liu http://www.vithon.org/tutorial/2.5/node7.html
3 of 11 08/31/2011 07:39 AM
nh phn function vi thng s l hai phn t u ca dy, ri sau vi gi tr tr
v ny vi phn t k, v c th. V d, tnh tng ca cc s t 1 n 10:
>>> def add(x,y): return x+y
...
>>> reduce(add, range(1, 11))
55
Nu ch c mt phn t trong dy, gi tr ca n s c tr v; nu dy rng,
bit l s c nng.
C th truyn thm thng s th ba cho bit gi tr ban u. Trong trng
hp , gi tr ny s c tr v nu dy rng, v hm s c p dng cho gi
tr ban u, v gi tr ca phn t u ca dy, ri vi gi tr c tr v vi gi
tr ca phn t k, v c th. V d,
>>> def sum(seq):
... def add(x,y): return x+y
... return reduce(add, seq, 0)
...
>>> sum(range(1, 11))
55
>>> sum([])
0
ng dng nh ngha ca v d ny v sum(): v vic cng cc con s l mt
nhu cu chung, mt hm c sn sum(sequence) c cung cp, v hoc ng
y nh vy. T phin bn 2.3.
5.1.4 Gp danh sch
Vic gp danh sch (list comprehension) cung cp mt cch xc tch to
danh sch m khng cn dng ti map(), filter() hoc lambda. Kt qu l
khai bo danh sch kiu ny thng d hiu hn nhng danh sch to ra t
nhng cch kia. Mi gp danh sch cha mt biu thc, theo sau bi v for , ri
khng c hoc c cc v for hoc if . Kt qu s l mt danh sch c tr v
t vic nh gi biu thc trong ng cnh ca cc v for v if theo sau n. Nu
biu thc tr v mt tuple, n phi c t trong ngoc.
>>> 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]
5. Cu trc d liu http://www.vithon.org/tutorial/2.5/node7.html
4 of 11 08/31/2011 07:39 AM
[[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[i]*vec2[i] for i in range(len(vec1))]
[8, 12, -54]
Cch gp danh sch uyn chuyn hn nhiu so vi map() v c th c p
dng cho cc biu thc phc tp v cc hm lng nhau:
>>> [str(round(355/113.0, i)) for i in range(1,6)]
['3.1', '3.14', '3.142', '3.1416', '3.14159']
5.2 del cu lnh
C mt cch b mt phn t ra khi danh sch da trn ch mc ca n,
thay v gi tr: cu lnh del . Cch ny khc vi phng thc pop()tr v mt
gi tr. Cu lnh del cng c th c s dng b cc ming ct (slice) khi
danh sch hoc xa ton b danh sch (iu m chng ta lm trc bng
cch gn mt danh sch rng vo ming ct). V d:
>>> a = [-1, 1, 66.25, 333, 333, 1234.5]
>>> del a[0]
>>> a
[1, 66.25, 333, 333, 1234.5]
>>> del a[2:4]
>>> a
[1, 66.25, 1234.5]
>>> del a[:]
>>> a
[]
del cng c th c dng xa hon ton cc bin:
>>> del a
Tham chiu ti tn a sau s to ra li (t nht cho n khi mt gi tr khc
c gn vo cho n). Chng ta s thy cc cch dng khc vi del sau ny.
5. Cu trc d liu http://www.vithon.org/tutorial/2.5/node7.html
5 of 11 08/31/2011 07:39 AM
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', # <-- note trailing comma
>>> len(empty)
0
>>> len(singleton)
1
>>> singleton
('hello',)
Cu lnh t = 12345, 54321, 'hello!' l mt v d ca vic ng gi tuple
(tuple packing): cc gi tr 12345, 54321 v 'hello!' c gi li vo trong
mt tuple. V qu trnh ngc:
>>> x, y, z = t
5. Cu trc d liu http://www.vithon.org/tutorial/2.5/node7.html
6 of 11 08/31/2011 07:39 AM
V n c gi l tho dy. Vic tho dy yu cu danh sch cc bin bn tri
c cng s phn t nh ln ca dy. Ch rng php a gn (multiple
assignment) tht ra ch l s tng hp ca vic gi tuple v tho dy.
C mt im khng i xng y: vic gi nhiu gi tr lun lun to mt
tuple, nhng php tho ra c th c p dng cho mi dy (chui, danh sch,
tuple).
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
5. Cu trc d liu http://www.vithon.org/tutorial/2.5/node7.html
7 of 11 08/31/2011 07:39 AM
dng lm kha nu n ch cha chui, s, hoc tuple; nu tuple cha bt k mt
i tng kh bin no th n khng th c dng lm kha. Bn khng th
dng danh sch lm kha, v danh sch c th c thay i ngay ti ch vi
php gn vo ch mc, php gn ming ct, hoc cc phng thc khc nh
append() v extend().
D nht l ngh v t in nh mt tp hp khng th t ca cc b kha: gi tr
, vi iu kin l kha phi l duy nht (trong cng mt t in). Mt cp ngoc
nhn to mt t in rng: {}. t mt lot cc cm kha:gi tr phn bit bi
du phy vo trong ngoc nhn to nn cc cp kha:gi tr ban u cho t
in; y cng l cch m t in c xut ra.
Cng vic chnh ca t in l cha mt gi tr vo mt kha no v ly li
gi tr t kha . Cng c th xa mt cp kha:gi tr vi del. Nu bn cha
vo mt kha c sn, gi tr c s b mt. Ly gi tr t mt kha khng tn
ti s gy nn li.
Phng thc keys() ca i tng t in tr v mt danh sch cc kha
c dng trong t in, theo mt th t bt k (nu bn mun chng c sp
xp, ch cn p dng phng thc sort() vo danh sch cc kha). kim tra
xem mt kha c trong t in hay khng, c th dng phng thc has_key()
hoc t kha in .
y l mt v d nh v cch dng t in:
>>> tel = {'jack': 4098, 'sape': 4139}
>>> tel['guido'] = 4127
>>> tel
{'sape': 4139, 'guido': 4127, 'jack': 4098}
>>> tel['jack']
4098
>>> del tel['sape']
>>> tel['irv'] = 4127
>>> tel
{'guido': 4127, 'irv': 4127, 'jack': 4098}
>>> tel.keys()
['guido', 'irv', 'jack']
>>> tel.has_key('guido')
True
>>> 'guido' in tel
True
Phng thc dict() dng to t in trc tip t cc danh sch cc cm
kha-gi tr cha trong tuple. Khi cc cm c mt mu no , vic gp danh
sch c th ch ra ngn gn danh sch kha-gi tr.
>>> dict([('sape', 4139), ('guido', 4127), ('jack', 4098)])
{'sape': 4139, 'jack': 4098, 'guido': 4127}
>>> dict([(x, x**2) for x in (2, 4, 6)]) # use a list comprehension
{2: 4, 4: 16, 6: 36}
5. Cu trc d liu http://www.vithon.org/tutorial/2.5/node7.html
8 of 11 08/31/2011 07:39 AM
phn sau ca bi ch dn chng ta s tm hiu v cc biu thc b to thch
hp hn vi vic cung cp cc cp kha-gi tr vo hm khi to dict() .
Khi m kha l nhng chui n gin, i khi n s d hn nu ch nh cc
cm bng thng s t kha:
>>> dict(sape=4139, guido=4127, jack=4098)
{'sape': 4139, 'jack': 4098, 'guido': 4127}
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
Khi lp qua mt dy, v tr ch mc v gi tr tng ng c th c ly ra cng
lc bng hm enumerate() .

>>> for i, v in enumerate(['tic', 'tac', 'toe']):
... print i, v
...
0 tic
1 tac
2 toe
lp qua hai hoc nhiu dy cng lc, cc phn t c th c ghp vi nhau
bng hm 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.
lp qua mt dy theo th t o, u tin ch nh dy theo th t xui,
ri gi hm reversed() .
>>> for i in reversed(xrange(1,10,2)):
... print i
...
5. Cu trc d liu http://www.vithon.org/tutorial/2.5/node7.html
9 of 11 08/31/2011 07:39 AM
9
7
5
3
1
lp qua mt dy theo th t sp xp, dng hm sorted() v n s tr v
mt danh sch sp xp trong khi vn danh sch gc nguyn vn.
>>> basket = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana']
>>> for f in sorted(set(basket)):
... print f
...
apple
banana
orange
pear
5.7 Bn thm v iu kin
iu kin dng trong cc cu lnh while v if c th cha bt k ton t no,
khng ch l php so snh.
Cc ton t so snh in v not in kim tra xem gi tr c mt (hoc khng c
mt) trong mt dy. Ton t is v is not so snh xem hai i tng c phi
cng l mt i tng hay khng; vic ny ch quan trng i vi cc i tng
kh bin nh danh sch. Mi ton t so snh c cng u tin, thp hn ca
cc ton t s.
So snh c th c ni vi nhau. V d nh, a < b == c kim tra xem a nh
hn b v hn na b bng vi c.
Php so snh c th c ghp vi nhau bng ton t Boolean and v or, v kt
qu ca php so snh (hoc ca mi biu thc Boolean) c th c o ngc
vi not. Cc ton t ny c u tin thp hn cc ton t so snh; gia chng,
not c u tin cao nht v or thp nht, cho A and not B or C tng
ng vi (A and (not B)) or C. Nh mi khi, du ngoc n c th c
dng cho bit kt cu ng .
Cc ton t Boolean and v or cn c gi l on mch (short-circuit) ton
t: ton hng ca chng c nh gi t tri qua phi, v vic nh gi dng
li ngay khi kt qu c xc nh. V d nh, nu A v C l ng nhng B l
sai, A and B and C khng nh gi biu thc C. Khi dng nh mt gi tr chung
chung v khng phi nh mt Boolean, gi tr tr v ca mt ton t on
mch l thng s c nh gi cui cng.
C th gn kt qu ca mt php so snh hoc mt biu thc Boolean vo mt
bin. V d,
5. Cu trc d liu http://www.vithon.org/tutorial/2.5/node7.html
10 of 11 08/31/2011 07:39 AM
>>> string1, string2, string3 = '', 'Trondheim', 'Hammer Dance'
>>> non_null = string1 or string2 or string3
>>> non_null
'Trondheim'
Ch rng trong Python, khc vi C, php gn khng th c mt trong biu
thc. Cc lp trnh vin C s khng hi lng vi vic ny, nhng n trnh mt
nhm ln cc li thng gp trong chng trnh C: nhp vo = trong mt biu
thc khi m == c nhm ti.
5.8 So snh dy v cc kiu khc
i tng dy c th c so snh vi i tng khc cng kiu dy. S so snh
dng t in th t: u tin hai phn t u c so snh, v nu chng khc
nhau th kt qu c xc nh; nu chng bng nhau th hai phn t k s c
so snh v c th, cho n cui mt trong hai dy. Nu hai phn t c so snh
li l hai phn dy cng kiu, php so snh t in li c thc hin quy
nh vy. Nu mi phn t trong hai dy u bng nhau th chng c coi l
bng nhau. Nu mt dy l dy con ban u ca dy kia, th dy ngn hn s l
dy b hn. Th t t in i vi chui s dng th t ASCII cho tng k t.
Mt vi v d v vic so snh dy cng kiu:
(1, 2, 3) < (1, 2, 4)
[1, 2, 3] < [1, 2, 4]
'ABC' < 'C' < 'Pascal' < 'Python'
(1, 2, 3, 4) < (1, 2, 4)
(1, 2) < (1, 2, -1)
(1, 2, 3) == (1.0, 2.0, 3.0)
(1, 2, ('aa', 'ab')) < (1, 2, ('abc', 'a'), 4)
Lu rng so snh cc i tng khc kiu cng c chp nhn. Kt qu c
th on c nhng ngoi mun: cc kiu c xp theo th t tn ca
chng. Do , mt danh sch (list) lun nh hn mt chui (string), v mt
chui lun nh hn mt tuple, v.v....
5.1
Cc kiu s ln ln c so snh theo
gi tr ca chng, do 0 bng 0.0, v.v...
Ch thch
... v.v...
5.1
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.
5. Cu trc d liu http://www.vithon.org/tutorial/2.5/node7.html
11 of 11 08/31/2011 07:39 AM
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
Vic ny s khng nhp trc tip cc tn hm nh ngha trong fibo vo bng
6. M-un http://www.vithon.org/tutorial/2.5/node8.html
1 of 10 08/31/2011 10:26 AM
k hiu (symbol table); n ch nhp tn m-un fibo m thi. Dng tn
m-un bn c th truy cp cc hm:
>>> fibo.fib(1000)
1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987
>>> fibo.fib2(100)
[1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
>>> fibo.__name__
'fibo'
Nu bn nh dng mt hm thng xuyn, th bn c th gn n vo mt tn
cc b:
>>> fib = fibo.fib
>>> fib(500)
1 1 2 3 5 8 13 21 34 55 89 144 233 377
6.1 Bn thm v m-un
M-un c th cha cc cu lnh kh thi cng nh cc nh ngha hm. Cc
cu lnh ny nhm mc ch khi to m-un. Chng s ch c chy ln u
m-un c nhp u .
6.1
Mi m-un c mt bng k hiu ring ca n v c dng nh bng ton cc
i vi mi hm c nh ngha trong m-un. Do , tc gi ca mt m-un
c th s dng cc bin ton cc trong m-un m khng phi lo lng v vic
trng lp vi cc bin ton cc ca ngi dng. Mt khc, nu bn bit bn
ang lm g, bn c th truy cp vo cc bin ton cc ca m-un vi cng
mt cch dng truy cp cc hm ca n. modname.itemname.
M-un c th nhp cc m-un khc. Thng thng (nhng khng bt buc)
ta hay tt c cc lnh import u mt m-un (hoc kch bn). Cc tn ca
m-un b nhp c t trong bng k hiu ton cc ca m-un nhp n.
C mt bin th ca cu lnh import nhp nhiu tn trc tip t mt m-un
vo trong bng k hiu ca m-un nhp. V d:
>>> from fibo import fib, fib2
>>> fib(500)
1 1 2 3 5 8 13 21 34 55 89 144 233 377
Cu lnh ny khng a tn m-un b nhp vo bng k hiu cc b (do
trong v d ny, fibo cha c nh ngha)
V mt bin th khc nhp tt c cc tn t mt m-un:
>>> from fibo import *
>>> fib(500)
1 1 2 3 5 8 13 21 34 55 89 144 233 377
6. M-un http://www.vithon.org/tutorial/2.5/node8.html
2 of 10 08/31/2011 10:26 AM
Cu lnh ny nhp tt c mi tn tr nhng tn bt u bng du gch chn
(_).
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.
6.1.2 Cc tp tin Python `` dch''
Nh mt cch quan trng tng tc qu trnh khi ng ca cc chng trnh
ngn c dng nhiu m-un chun, nu tp tin c tn spam.pyc tn ti trong
th mc m spam.py c tm thy, tp tin ny c gi nh l phin bn
c ``bin dch byte'' (byte-compile) ca m-un spam. Thi gian thay i ca
phin bn spam.py dng to spam.pyc c lu li trong spam.pyc, v tp
tin .pyc s b b qua nu chng khng khp nhau.
Thng thng, bn khng cn lm g c to tp tin spam.pyc . Khi no
spam.py c bin dch thnh cng, Python s th ghi phin bn bin dch
ra spam.pyc. Nu vic ghi ny tht bi th cng khng c li g xy ra; nu v l
do g m tp tin khng c ghi y , tp tin spam.pyc s b nh du l
khng hp l v s b b qua sau ny. Ni dung ca tp tin spam.pyc khng
ph thuc vo h thng, do mt th mc m-un Python c th c chia x
vi nhiu my trn cc kin trc khc nhau.
Mt vi mo cho chuyn gia:
Khi trnh thng dch Python c chy vi c -O , m ti u c to v
lu trong cc tp tin .pyo . Trnh ti u ha hin ti khng gip g nhiu,
n ch b i cc lnh assert . Khi -O c dng, tt c m byte
(bytecode) u c ti u; .pyc b b qua v .py c bin dch ra m
byte ti u.
6. M-un http://www.vithon.org/tutorial/2.5/node8.html
3 of 10 08/31/2011 10:26 AM
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.
6.2 Cc m-un chun
Python c mt th vin cc m-un chun, c ni ti trong mt ti liu khc,
Tham kho th vin Python (t nay gi l ``Ti liu tham kho'''). Mt vi
m-un c chuyn thng vo trnh thng dch; chng cung cp cc tc v
khng nm trong phm vi chnh ca ngn ng nhng cng c to sn v hiu
qu cao hoc truy cp vo nhng chc nng ca h iu hnh v d nh cc
lnh gi h thng. Tp hp cc m-un ny l mt ty chn cu hnh l thuc
vo h thng. V d, m-un amoeba ch c trn cc h h tr Amoeba. Cn phi
nhc n m-un: sys, c a vo trong mi trnh thng dch Python. Cc
bin sys.ps1 v sys.ps2 nh ngha nhng chui c dng nh du nhc
chnh v ph:
>>> import sys
>>> sys.ps1
'>>> '
>>> sys.ps2
'... '
>>> sys.ps1 = 'C> '
C> print 'Yuck!'
Yuck!
C>
Hai bin ny ch c nh ngha khi trnh thng dch chy ch tng tc.
6. M-un http://www.vithon.org/tutorial/2.5/node8.html
4 of 10 08/31/2011 10:26 AM
Bin sys.path l mt danh sch cc chui quyt nh ng dn tm kim cc
m-un ca trnh thng dch. N c khi to theo ng dn mc nh t
bin mi trng PYTHONPATH, hoc t mt gi tr c sn nu PYTHONPATH
khng c thit lp. Bn c th sa n bng cch dng cc cng c trn danh
sch:
>>> import sys
>>> sys.path.append('/ufs/guido/lib/python')
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']
Khng c thng s, dir() lit k cc tn bn nh ngha:
>>> a = [1, 2, 3, 4, 5]
>>> import fibo
>>> fib = fibo.fib
>>> dir()
['__builtins__', '__doc__', '__file__', '__name__', 'a', 'fib', 'fibo', 'sys']
Lu rng n lit k mi loi tn: bin, m-un, hm, v.v...
dir() khng lit k tn ca cc hm v bin c sn. Nu bn mun c danh
sch ca chng, th chng c nh ngha trong m-un chun __builtin__:
>>> import __builtin__
>>> dir(__builtin__)
['ArithmeticError', 'AssertionError', 'AttributeError', 'DeprecationWarning',
'EOFError', 'Ellipsis', 'EnvironmentError', 'Exception', 'False',
'FloatingPointError', 'FutureWarning', 'IOError', 'ImportError',
'IndentationError', 'IndexError', 'KeyError', 'KeyboardInterrupt',
'LookupError', 'MemoryError', 'NameError', 'None', 'NotImplemented',
'NotImplementedError', 'OSError', 'OverflowError',
6. M-un http://www.vithon.org/tutorial/2.5/node8.html
5 of 10 08/31/2011 10:26 AM
'PendingDeprecationWarning', 'ReferenceError', 'RuntimeError',
'RuntimeWarning', 'StandardError', 'StopIteration', 'SyntaxError',
'SyntaxWarning', 'SystemError', 'SystemExit', 'TabError', 'True',
'TypeError', 'UnboundLocalError', 'UnicodeDecodeError',
'UnicodeEncodeError', 'UnicodeError', 'UnicodeTranslateError',
'UserWarning', 'ValueError', 'Warning', 'WindowsError',
'ZeroDivisionError', '_', '__debug__', '__doc__', '__import__',
'__name__', 'abs', 'apply', 'basestring', 'bool', 'buffer',
'callable', 'chr', 'classmethod', 'cmp', 'coerce', 'compile',
'complex', 'copyright', 'credits', 'delattr', 'dict', 'dir', 'divmod',
'enumerate', 'eval', 'execfile', 'exit', 'file', 'filter', 'float',
'frozenset', 'getattr', 'globals', 'hasattr', 'hash', 'help', 'hex',
'id', 'input', 'int', 'intern', 'isinstance', 'issubclass', 'iter',
'len', 'license', 'list', 'locals', 'long', 'map', 'max', 'min',
'object', 'oct', 'open', 'ord', 'pow', 'property', 'quit', 'range',
'raw_input', 'reduce', 'reload', 'repr', 'reversed', 'round', 'set',
'setattr', 'slice', 'sorted', 'staticmethod', 'str', 'sum', 'super',
'tuple', 'type', 'unichr', 'unicode', 'vars', 'xrange', 'zip']
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/ Top-level package
__init__.py Initialize the sound package
Formats/ Subpackage for file format conversions
__init__.py
wavread.py
wavwrite.py
aiffread.py
aiffwrite.py
auread.py
auwrite.py
...
6. M-un http://www.vithon.org/tutorial/2.5/node8.html
6 of 10 08/31/2011 10:26 AM
Effects/ Subpackage for sound effects
__init__.py
echo.py
surround.py
reverse.py
...
Filters/ Subpackage for filters
__init__.py
equalizer.py
vocoder.py
karaoke.py
...
Khi nhp mt gi, Python tm trong cc th mc t sys.path tm th mc
con ca gi.
Cc tp tin __init__.py l cn thit cho Python bit cc th mc cha cc gi;
vic ny c t ra trnh cc th mc vi tn chung, v d nh "string",
v tnh che mt m-un hp l xut hin sau trong ng dn tm kim. Trong
trng hp n gin nht, __init__.py c th ch l mt tp tin rng, nhng n
cng c th thc thi cc m thit lp ca gi hoc thit lp bin __all__ , s
c nhc n sau.
Ngi dng gi ny c th nhp tng m-un ring l t gi, v d:
import Sound.Effects.echo
N s np m-un con Sound.Effects.echo. N phi c tham chiu bng
tn y .
Sound.Effects.echo.echofilter(input, output, delay=0.7, atten=4)
Cch nhp m-un con khc l:
from Sound.Effects import echo
N cng np lun m-un con echo, v lm cho n c th c truy cp m
khng cn phn tn gi, do n c th c dng nh sau:
echo.echofilter(input, output, delay=0.7, atten=4)
Mt bin th khc l nhp hm hoc bin mnh mun mt cch trc tip:
from Sound.Effects.echo import echofilter
Mt ln na, lnh ny np m-un con echo, nhng n lm hm echofilter()
c th c s dng trc tip:
echofilter(input, output, delay=0.7, atten=4)
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
6. M-un http://www.vithon.org/tutorial/2.5/node8.html
7 of 10 08/31/2011 10:26 AM
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"]
iu ny c ngha l from Sound.Effects import * s nhp ba m-un c
ch nh t gi Sound .
Nu __all__ khng c nh ngha, cu lnh from Sound.Effects import *
does khng nhp mi m-un con t gi Sound.Effects vo vng tn hin ti;
n ch m bo rng gi Sound.Effects c nhp (c th chy cc m
khi to trong __init__.py) v sau nhp cc tn c nh ngha trong gi.
N bao gm cc tn (v m-un con c np) c nh ngha bi
__init__.py. N cng gm cc m-un con ca gi c np bi cu lnh
import trc. Xem on m ny:
import Sound.Effects.echo
import Sound.Effects.surround
from Sound.Effects import *
Trong v d ny, cc m-un echo v surround c nhp vo vng tn hin
6. M-un http://www.vithon.org/tutorial/2.5/node8.html
8 of 10 08/31/2011 10:26 AM
ti v chng c nh ngha trong gi Sound.Effects khi cu lnh
from...import c thc thi. (Cng s c cng kt qu khi __all__ c nh
ngha.)
Lu l bnh thng vic nhp * t mt m-un hay gi c coi l xu, v n
hay dn ti cc m kh c. Tuy nhin, khi dng trong mt phin lm vic
tng tc th n gip tit kim cng nhp phm, v mt vi m-un c thit
k ch xut cc tn theo mt vi mu c th.
Nh rng, khng c g sai tri vi vic dng from Package import
specific_submodule! ng ra, y l cch vit c khuyn khch tr khi
m-un nhp (importing module) cn dng m-un con c cng tn mt gi
khc.
6.4.2 Tham chiu ni trong gi
Cc m-un con thng cn tham chiu ln nhau. V d, M-un surround c
th s dng m-un echo . Trong thc t, nhng tham chiu ny qu ph bin
n ni cu lnh import u tin s tm trong gi cha (containing package)
trc khi tm trong ng dn tm kim m-un chun. Do , m-un
surround c th n gin dng import echo hay from echo import
echofilter. Nu m-un c nhp (imported module) khng th tm ra trong
gi cha (l gi m m-un hin ti l mt m-un con), cu lnh import tm
mt m-un cp cao nht c cng tn.
Khi cc gi c cu trc thnh cc gi con (nh gi Sound trong v d), khng
c ng tt tham chiu ti cc m-un con ca cc gi k cn - tn y
ca gi con phi c ch nh. V d, nu m-un Sound.Filters.vocoder cn
dng m-un echo trong gi Sound.Effects , n c th dng from
Sound.Effects import echo.
Bt u t Python 2.5, ngoi vic nhp tng i hiu ngm (implicit relative
import) ni, bn c th vit lnh nhp tng i xc nh (explicit relative
import) vi kiu from module import name ca cu lnh nhp. Cc lnh nhp
tng i xc nh dng chm u ch nh cc gi hin ti v gi cha c
mt trong cu lnh nhp. V d t m-un surround , bn s dng:
from . import echo
from .. import Formats
from ..Filters import equalizer
Lu c hai lnh nhp tng i xc nh v hiu ngm u da vo tn ca
m-un hin ti. V tn ca m-un chnh lun lun l "__main__", m-un
c nhm d dng nh m-un chnh ca mt chng trnh Python nn lun
lun cng cu lnh nhp tuyt i.
6.4.3 Gi trong nhiu th mc
6. M-un http://www.vithon.org/tutorial/2.5/node8.html
9 of 10 08/31/2011 10:26 AM
Gi cn c thm mt thuc tnh c bit khc, __path__. N c khi to l
danh sch cha tn ca th mc cha tp tin __init__.py ca gi trc khi m
trong tp tin c thc thi. Bin ny c th c thay i; lm nh vy s
nh hng cc tm kim m-un v gi con cha trong gi ny trong tng lai.
Mc d tnh nng ny khng thng c dng, n c th c tn dng m
rng tp hp cc m-un tm thy trong mt gi.
Ghi ch
... u .
6.1
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.
6. M-un http://www.vithon.org/tutorial/2.5/node8.html
10 of 10 08/31/2011 10:26 AM
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.'"
7. Vo v ra http://www.vithon.org/tutorial/2.5/node9.html
1 of 7 08/31/2011 10:26 AM
>>> 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'))"
y l hai cch vit mt bng bnh phng v lp phng:
>>> for x in range(1, 11):
... print repr(x).rjust(2), repr(x*x).rjust(3),
... # Note trailing comma on previous line
... print repr(x*x*x).rjust(4)
...
1 1 1
2 4 8
3 9 27
4 16 64
5 25 125
6 36 216
7 49 343
8 64 512
9 81 729
10 100 1000
>>> for x in range(1,11):
... print '%2d %3d %4d' % (x, x*x, x*x*x)
...
1 1 1
2 4 8
3 9 27
4 16 64
5 25 125
6 36 216
7 49 343
8 64 512
9 81 729
10 100 1000
7. Vo v ra http://www.vithon.org/tutorial/2.5/node9.html
2 of 7 08/31/2011 10:26 AM
(Ch mt khong trng c thm vo gia cc ct theo cch hot ng ca
print : n lun lun thm khong trng gia cc thng s.)
V d ny biu din phng thc rjust() ca cc i tng chui, n canh phi
mt chui vo trong trng vi rng xc nh bng cch thm khong trng
vo bn tri. Cc phng thc tng t khc gm ljust() v center(). Cc
phng thc ny khng vit g c, chng ch tr v mt chui mi. Nu chui
nhp vo qu di, chng cng khng ct n i, m tr v n nguyn vn; iu
ny thng s ph hng b cc ca bn, nhng vn tt hn l ni di v mt gi
tr. (Nu bn tht s mun ct b bn c th thm php ct ming, nh
"x.ljust(n)[:n]".)
C mt phng thc khc, zfill(), n m khng vo bn tri mt chui s.
N hiu cc du cng v tr:
>>> '12'.zfill(5)
'00012'
>>> '-3.14'.zfill(7)
'-003.14'
>>> '3.14159265359'.zfill(5)
'3.14159265359'
Dng ton t % s ging nh vy:
>>> import math
>>> print 'The value of PI is approximately %5.3f.' % math.pi
The value of PI is approximately 3.142.
Nu c nhiu hn mt nh dng trong chui, bn cn truyn mt b ton hng
bn phi, nh trong v d ny:
>>> table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 7678}
>>> for name, phone in table.items():
... print '%-10s ==> %10d' % (name, phone)
...
Jack ==> 4098
Dcab ==> 7678
Sjoerd ==> 4127
Hu ht cc nh dng hot ng nh trong C v yu cu bn truyn kiu thch
hp; nu khng, bn s nhn bit l thay v nhn (core dump). nh dng %s
d di hn: nu thng s tng ng khng phi l mt i tng chui, n s
c chuyn thnh chui qua hm c sn str() . Vic dng * truyn vo
rng v mc chnh xc nh l mt thng s nguyn ring cng c h tr. Cc
nh dng C %n v %p khng c h tr.
Nu bn c mt chui nh dng rt di v khng mun ct ra, c th bn s
mun tham chiu ti cc bin sp c nh dng qua tn, thay v v tr. Vic ny
c th c thc hin theo dng %(name)format, nh v d sau:
>>> table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 8637678}
7. Vo v ra http://www.vithon.org/tutorial/2.5/node9.html
3 of 7 08/31/2011 10:26 AM
>>> print 'Jack: %(Jack)d; Sjoerd: %(Sjoerd)d; Dcab: %(Dcab)d' % table
Jack: 4098; Sjoerd: 4127; Dcab: 8637678
Cch ny c bit hu dng khi i km vi hm c sn vars() mi, n tr v
mt t in cha tt c cc bin cc b.
7.2 c v vit tp tin
open() tr v mt i tng tp tin, v thng c dng vi hai thng s:
"open(filename, mode)".
>>> f=open('/tmp/workfile', 'w')
>>> print f
<open file '/tmp/workfile', mode 'w' at 80a0960>
Thng s th nht l mt chui cha tn tp tin. Thng s th hai l mt chui
khc cha mt vi k t xc nh cch thc tp tin s c dng. mode c th l
'r' khi tp s ch c c, 'w' ch c ghi (tp tin cng tn ang c s b
xa), v 'a' m tp tin thm vo cui; mi d liu ghi vo tp tin s c t
ng thm vo cui. 'r+' m tp tin c v ghi. Thng s mode l khng bt
buc; 'r' s c gi nh nu n b b qua.
Trong Windows v Macintosh, 'b' thm vo mode m tp tin ch nh phn,
cho nn cng c cc ch khc nh 'rb', 'wb', v 'r+b'. Windows phn bit
r cc tp tin vn bn v nh phn; k t ht dng (end-of-line) trong cc tp tin
vn bn c t ng thay i mt cht khi d liu c c hay ghi. Vic thay
i sau bc bnh phong (behind-the-scene) nh vy khng nh hng cc tp tin
vn bn ASCII, nhng n s ph d liu nh phn nh trong cc tp tin JPEG hay
hm EXE . Cn cn thn dng ch nh phn khi c v ghi cc tp tin nh vy.
7.2.1 Phng thc ca i tng tp tin
Cc v d trong mc ny s gi s mt i tng tp tin f c to.
c ni dung tp tin, gi f.read(size), n c mt s lng d liu v tr v
mt chui. size l mt thng s s nguyn khng bt buc. Khi size b b qua hoc
m, ton b ni dung tp tin s c c v tr v; bn s gp vn nu tp tin
ln gp i b nh ca my bn. Ngc li, nhiu nht size byte s c c v
tr v. Nu n cui tp tin, f.read() s tr v mt chui rng ("").
>>> f.read()
'This is the entire file.\n'
>>> f.read()
''
f.readline() c mt dng t tp tin; k t dng mi (\n) c gi li cui
chui, v s ch b b qua dng cui ca tp tin nu tp tin khng kt thc
bng mt dng mi. iu ny lm gi tr tr v r rng; nu f.readline() tr v
mt chui rng c ngha l ng cui tp tin, trong khi mt dng trng th
7. Vo v ra http://www.vithon.org/tutorial/2.5/node9.html
4 of 7 08/31/2011 10:26 AM
c biu din bi '\n', mt chui ch cha duy nht mt k t dng mi.
>>> f.readline()
'This is the first line of the file.\n'
>>> f.readline()
'Second line of the file\n'
>>> f.readline()
''
f.readlines() tr v mt danh sch tt c cc dng trong tp tin. Nu truyn
mt tham s khng bt buc sizehint, n s c nhiu byte t tp tin v thm
mt cht hon tt mt dng, v tr v cc dng c c. iu ny
thng c dng c mt cch hiu qu tng dng mt trong mt tp tin
ln m khng cn phi np ton b tp tin vo b nh. Ch c cc dng ton vn
mi c tr v.
>>> f.readlines()
['This is the first line of the file.\n', 'Second line of the file\n']
Mt cch khc c cc dng l lp qua i tng tp tin. N rt tit kim b
nh, nhanh, v c m n gin:
>>> for line in f:
print line,

This is the first line of the file.
Second line of the file
Cch ny n gin hn nhng khng cho bn iu khin cch c. V hai cch
ny qun l b m dng khc nhau, chng khng nn c dng chung.
f.write(string) vit ni dung ca string vo tp tin, tr v None.
>>> f.write('This is a test\n')
vit mt th khc khng phi l chui, n s cn c chuyn thnh mt chui
trc:
>>> value = ('the answer', 42)
>>> s = str(value)
>>> f.write(s)
f.tell() tr v mt s nguyn cho bit v tr hin ti ca i tng tp tin, tnh
theo byte t u tp tin. di chuyn v tr, dng "f.seek(offset, from_what)". V
tr c tnh t tng ca offset v im tham chiu; iu tham chiu c xc nh
bi thng s from_what . Gi tr from_what 0 tnh t u tp tin, 1 dng v tr hin
ti, v 2 tnh t v tr cui tp tin. from_what c th b b qua v mc nh l 0,
im tham chiu l u tp tin.
>>> f = open('/tmp/workfile', 'r+')
>>> f.write('0123456789abcdef')
>>> f.seek(5) # Go to the 6th byte in the file
7. Vo v ra http://www.vithon.org/tutorial/2.5/node9.html
5 of 7 08/31/2011 10:26 AM
>>> f.read(1)
'5'
>>> f.seek(-3, 2) # Go to the 3rd byte before the end
>>> f.read(1)
'd'
Khi bn dng xong, gi f.close() ng n li v gii phng ti nguyn
h thng s dng khi m tp tin. Sau khi gi f.close(), mi cch dng i
tng tp tin s t ng tht bi.
>>> f.close()
>>> f.read()
Traceback (most recent call last):
File "<stdin>", line 1, in ?
ValueError: I/O operation on closed file
Cc i tng tp tin c thm cc phng thc ph nh isatty() v
truncate() khng c thng xuyn dng; tham kho ti liu th vin bit
thm v cc i tng tp tin.
7.2.2 pickle m-un
Cc chui c th c ghi hoc c d dng t mt tp tin. Cc s cn mt t c
gng hn, v phng thc read() ch tr v chui, v cn c truyn vo mt
hm nh int(), n s nhn mt chui nh '123' v tr v gi tr s 123 ca n.
Tuy nhin, khi bn mun lu cc kiu d liu phc tp hn nh danh sch, t
in, hoc cc i tng, vic ny tr nn rc ri hn nhiu.
Thay v ngi dng lun vit v g ri m lu cc kiu d liu phc tp,
Python cung cp mt m-un chun gi l pickle. y l mt m-un tuyt diu
c th nhn hu ht mi i tng Python (ngay c mt vi dng m Python!), v
chuyn n thnh mt chui; qu trnh ny c gi l gim (pickling). To li i
tng t mt chui c gi l vt (unpickling). Gia vic gim v vt, biu din
dng chui ca i tng c th c lu vo tp tin, hoc gi qua mng n
mt my xa.
Nu bn c mt i tng x, v mt i tng tp tin f c m ghi vo,
cch n gin nht gim i tng ch cn mt dng m:
pickle.dump(x, f)
vt i tng ra, nu f l mt i tng tp tin c m c:
x = pickle.load(f)
(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;
7. Vo v ra http://www.vithon.org/tutorial/2.5/node9.html
6 of 7 08/31/2011 10:26 AM
thut ng trong ngnh gi l i tng bn . V pickle c s dng rng ri,
nhiu tc gi khi m rng Python cn thn m bo rng cc kiu d liu
mi v d nh ma trn c th c gim v vt ng n.
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. Vo v ra http://www.vithon.org/tutorial/2.5/node9.html
7 of 7 08/31/2011 10:26 AM
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
B phn tch lp li dng gy li v hin th mt mi tn nh tr vo im u tin li
c pht hin. Li nm du hiu pha trc mi tn: trong v d trn, li c pht
hin t kha print, v thiu mt du hai chm (":") trc . Tn tp tin vo s
dng c hin th bn bit tm li ch no nu u vo l t mt kch bn.
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,
8. Li v bit l http://www.vithon.org/tutorial/2.5/node10.html
1 of 7 08/31/2011 10:27 AM
nhng khng nht thit ng vi cc bit l do ngi dng nh ngha (mc d l
mt quy c hu dng). Cc tn bit l chun l nhng t nh danh c sn (khng
phi l t kha).
Phn cn li cho bit chi tit v kiu bit l v chuyn g gy ra n.
Phn trc ca thng ip li cho bit hon cnh khi xy ra bit l, dng ln ngc
ngn xp (stack traceback). Bnh thng n cha mt ln ngc ngn xp lit k cc
dng ngun; tuy nhin, n s khng hin th cc dng c t u vo chun.
Tham kho th vin Python lit k cc bit l c sn v ngha ca chng.
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..."
...
try (cu lnh) hot ng nh sau.
Trc tin, v try (cc cu lnh gia t kha try v except ) c thc thi.
Nu khng c bit l no xy ra, v except c b qua v cu lnh try kt
thc.
Nu trong khi thc thi v try xy ra bit l, phn cn li ca v c b qua. Sau
nu kiu bit l hp vi kiu c ch nh sau t kha except , th v except
c thc thi, v ri vic thc thi tip tc sau cu lnh try .
Nu bit l xy ra khng hp vi bit l c ch nh v except, n s c
truyn ra cc cu lnh try bn ngoi; nu khng c on m x l no, n l
mt bit l khng c x l v vic thc thi dng li vi mt thng bo nh
trn.
A try (cu lnh) c th c nhiu hn mt v except, ch r cch x l cho nhng
bit l khc nhau. Nhiu nht l mt on x l (handler) s c thc thi. Cc on
x l ch x l bit l xy ra trong v try tng ng, khng x l cc bit l trong cc
on x l khc ca cng cu lnh try . V except c th nh danh nhiu bit l
trong mt b (tuple), v d:
... except (RuntimeError, TypeError, NameError):
... pass
8. Li v bit l http://www.vithon.org/tutorial/2.5/node10.html
2 of 7 08/31/2011 10:27 AM
V except cui cng c th b qua tn bit l, c tc dng nh l mt thay th
(wildcard). Phi ht sc cn trng khi dng n, v n c th d dng che i li lp
trnh tht! N cng c th c dng in thng bo li v sau nng bit l li
(re-raise exception) (nhm cho php ni gi x l bit l):
import sys
try:
f = open('myfile.txt')
s = f.readline()
i = int(s.strip())
except IOError, (errno, strerror):
print "I/O error(%s): %s" % (errno, strerror)
except ValueError:
print "Could not convert data to an integer."
except:
print "Unexpected error:", sys.exc_info()[0]
raise
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()
Vic dng v else tt hn l thm m vo v try v n trnh vic v tnh bt mt
bit l khng c nng t m c bo v trong cu lnh try ... except .
Khi mt bit l xy ra, n c th c mt gi tr gn lin, cn c bit n nh l
thng sca bit l. S c mt v kiu ca thng s ph thuc vo kiu bit l.
V except c th ch nh mt bin sau mt (hoc mt b) tn bit l. Bin c
gn vi mt trng hp bit l (exception instance) vi cc thng s cha trong
instance.args. thun tin, trng hp bit l nh ngha __getitem__ v
__str__ cho cc thng s c th c truy xut v in ra trc tip m khng phi
tham chiu .args.
Nhng vic dng .args khng c khuyn khch. Thay vo , cch dng tt
nht l truyn mt thng s n l vo mt bit l (c th l mt b nu c nhiu
thng s) v gn n vo thuc tnh message . Ta cng c th to mt bit l trc v
thm cc thuc tnh vo n trc khi nng.
>>> try:
... raise Exception('spam', 'eggs')
... except Exception, inst:
... print type(inst) # the exception instance
... print inst.args # arguments stored in .args
8. Li v bit l http://www.vithon.org/tutorial/2.5/node10.html
3 of 7 08/31/2011 10:27 AM
... print inst # __str__ allows args to printed directly
... x, y = inst # __getitem__ allows args to be unpacked directly
... print 'x =', x
... print 'y =', y
...
<type 'instance'>
('spam', 'eggs')
('spam', 'eggs')
x = spam
y = eggs
Nu bit l c mt thng s, n s c in ra nh l phn cui (`chi tit') ca thng
ip ca nhng bit l khng c x l.
Cc phn x l bit l khng ch x l cc bit l xy ra ngay trong v try, m cn x
l c bit trong nhng hm c gi (trc tip hoc gin tip) trong v try. V d:
>>> def this_fails():
... x = 1/0
...
>>> try:
... this_fails()
... except ZeroDivisionError, detail:
... print 'Handling run-time error:', detail
...
Handling run-time error: integer division or modulo by zero
8.4 Nng bit l
raise (cu lnh) cho php nh lp trnh p xy ra mt bit l c ch nh. V d:
>>> raise NameError, 'HiThere'
Traceback (most recent call last):
File "<stdin>", line 1, in ?
NameError: HiThere
Thng s u tin cho raise ch nh bit l s c nng. Thng s (ty chn) th
hai ch nh thng s ca bit l. Hoc l, cc dng trn c th c vit raise
NameError('HiThere'). C hai dng u ng, nhng ngi ta c v chung dng
th hai hn.
Nu bn cn xc nh xem mt bit l c c nng cha nhng khng nh x l n,
dng n gin hn ca cu lnh raise cho php bn nng li (re-raise) bit l:
>>> try:
... raise NameError, 'HiThere'
... except NameError:
... print 'An exception flew by!'
... raise
...
An exception flew by!
Traceback (most recent call last):
File "<stdin>", line 2, in ?
NameError: HiThere
8. Li v bit l http://www.vithon.org/tutorial/2.5/node10.html
4 of 7 08/31/2011 10:27 AM
8.5 Bit l t nh ngha
Cc chng trnh c th t tn bit l ring bng cch to mt lp bit l mi. Cc
bit l thng nn k tha t lp Exception , trc tip hoc gin tip. V d:
>>> class MyError(Exception):
... def __init__(self, value):
... self.value = value
... def __str__(self):
... return repr(self.value)
...
>>> try:
... raise MyError(2*2)
... except MyError, e:
... print 'My exception occurred, value:', e.value
...
My exception occurred, value: 4
>>> raise MyError, 'oops!'
Traceback (most recent call last):
File "<stdin>", line 1, in ?
__main__.MyError: 'oops!'
Trong v d ny, mc nh __init__ ca Exception c nh ngha li. Cch
thc mi ch n gin to thuc tnh value . N thay th cch thc mc nh to thuc
tnh args .
Cc lp bit l c th c nh ngha lm bt k vic g nh cc lp khc, nhng
chng thng l n gin v ch cung cp mt s thuc tnh cha thng tin v li
cho cc phn x l bit l. Khi to mt m-un m c th nng vi li khc bit, cch
thng thng l to mt lp c s cho cc bit l c nh ngha bi m-un , v
k tha t to nhng lp bit l c th cho nhng trng hp li khc nhau:
class Error(Exception):
"""Base class for exceptions in this module."""
pass
class InputError(Error):
"""Exception raised for errors in the input.
Attributes:
expression -- input expression in which the error occurred
message -- explanation of the error
"""
def __init__(self, expression, message):
self.expression = expression
self.message = message
class TransitionError(Error):
"""Raised when an operation attempts a state transition that's not
allowed.
Attributes:
8. Li v bit l http://www.vithon.org/tutorial/2.5/node10.html
5 of 7 08/31/2011 10:27 AM
previous -- state at beginning of transition
next -- attempted new state
message -- explanation of why the specific transition is not allowed
"""
def __init__(self, previous, next, message):
self.previous = previous
self.next = next
self.message = message
a s bit l c nh ngha vi tn tn cng bng ``Error'', tng t nh cch t
tn ca cc bit l chun.
Nhiu m-un chun nh ngha bit l ring cho chng thng bo nhng li m
c th xy ra trong cc hm chng nh ngha. Thng tin thm v cc lp c trnh
by trong chng 9, ``Lp''.
8.6 nh ngha cch x l
try (cu lnh) c mt v khng bt buc khc vi mc ch nh ngha nhng tc v
dn dp (clean-up action) m s c thc hin trong mi trng hp. V d:
>>> try:
... raise KeyboardInterrupt
... finally:
... print 'Goodbye, world!'
...
Goodbye, world!
Traceback (most recent call last):
File "<stdin>", line 2, in ?
KeyboardInterrupt
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)
8. Li v bit l http://www.vithon.org/tutorial/2.5/node10.html
6 of 7 08/31/2011 10:27 AM
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'
Nh bn c th thy, v finally c thc thi trong mi trng hp. TypeError c
nng v chia hai chui khng c x l bi v except v v th nn c nng li sau
khi v finally c thc thi.
Trong cc ng dng thc th, v finally c dng tr li nhng ti nguyn
ngoi (nh tp tin, hoc kt ni mng), cho d vic s dng ti nguyn c thnh
cng hay khng.
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
Vn vi on m trn l n tp tin ng trong mt thi gian khng xc nh sau
khi on m kt thc. y khng phi l vn g trong cc on kch bn n
gin, nhng c th l mt vn phc tp i vi cc ng dng ln hn. Cu lnh
with cho php cc i tng nh tp tin c dng theo mt cch m bo chng s
c dn dp ng lc v ng n.
with open("myfile.txt") as f:
for line in f:
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.
8. Li v bit l http://www.vithon.org/tutorial/2.5/node10.html
7 of 7 08/31/2011 10:27 AM
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.
9.2 Phm vi trong Python v vng tn
Trc khi gii thiu lp, chng ta s cn hiu phm vi (scope) v vng tn
(namespace) hot ng nh th no v cc nh ngha lp s s dng chng. Kin thc
v vn ny cng rt hu dng vi nhng nh lp trnh Python chuyn nghip.
Bt u vi mt vi nh ngha.
9. Lp http://www.vithon.org/tutorial/2.5/node11.html
1 of 13 08/31/2011 10:27 AM
A namespace (vng tn) (vng tn) l nh x t tn vo i tng. a s cc vng tn
c ci t bng t in Python, nhng iu thng l khng quan trng (tr tc
), v c th s thay i trong tng lai. Cc v d vng tn nh: tp hp cc tn c
sn (cc hm nh abs(), v cc tn bit l c sn); cc tn ton c trong mt
m-un; cc tn ni b trong mt php gi hm. Theo ngha tp hp cc thuc
tnh ca mt i tng cng l mt vng tn. iu quan trng cn bit v vng tn l
tuyt i khng c quan h g gia cc vng tn khc nhau; v d hai m-un khc
nhau c th cng nh ngha hm ``maximize'' m khng s ln ln -- ngi dng
m-un phi thm tin t tn m-un trc khi gi hm.
Cng xin ni thm l t thuc tnh c dng ch mi tn theo sau du chm -- v
d, trong biu thc z.real, real l mt thuc tnh ca i tng z. Ni ng ra, tham
chiu ti tn trong mt m-un l cc tham chiu ti thuc tnh: trong biu thc
modname.funcname, modname l mt i tng m-un v funcname l mt thuc tnh
ca n. Trong trng hp ny, vic nh x gia cc thuc tnh ca m-un v cc tn
ton cc c nh ngha trong m-un tht ra rt n gin: chng dng chung mt
vng tn!
9.1
Thuc tnh c th l ch c, hoc c ghi. Trong trng hp sau, php gn vo thuc
tnh c th c thc hin. Cc thuc tnh m-un l c ghi: bn c th vit
"modname.the_answer = 42". Cc thuc tnh c ghi cng c th c xa i vi cu
lnh del . V d, "del modname.the_answer" s xa thuc tnh the_answer t i
tng tn modname.
Cc vng tn c to ra vo nhng lc khc nhau v c thi gian sng khc nhau.
Vng tn cha cc tn c sn c to ra khi trnh thng dch Python bt u, v
khng bao gi b xa i. Vng tn ton cc ca mt m-un c to ra khi nh
ngha m-un c c; bnh thng, vng tn m-un cng tn ti cho ti khi trnh
thng dch thot ra. Cc cu lnh c thc thi bi li gi lp cao nht ca trnh
thng dch, v c t mt kch bn hoc qua tng tc, c coi nh mt phn ca
m-un gi l __main__, cho nn chng cng c vng tn ring. (Cc tn c sn tht
ra cng tn ti trong mt m-un; c gi l __builtin__.)
Vng tn ni b ca mt hm c to ra khi hm c gi, v c xa i khi hm
tr v, hoc nng mt bit l khng c x l trong hm. D nhin, cc li gi hm
quy c vng tn ring ca chng.
A phm vi l mt vng vn bn ca mt chng trnh Python m mt vng tn c th
c truy cp trc tip. ``C th truy cp trc tip'' c ngha l mt tham chiu khng
y (unqualifed reference) ti mt tn s th tm tn trong vng tn.
Mc d phm vi c xc nh tnh, chng c dng mt cch ng. Vo bt k mt
lc no, c t nht ba phm vi lng nhau m vng tn ca chng c th c truy cp
trc tip: phm vi bn trong cng, c tm trc, cha cc tn ni b; cc vng tn
ca cc hm cha n, c tm bt u t phm vi cha n gn nht (nearest
enclosing scope); phm vi gia (middle scope), c tm k, cha cc tn ton cc ca
m-un; v phm vi ngoi cng (c tm sau cng) l vng tn cha cc tn c sn.
Nu mt tn c khai bo l ton cc, th mi tham chiu hoc php gn s i thng
vo phm vi gia cha cc tn ton cc ca m-un. Nu khng, mi bin c tm
thy ngoi phm vi trong cng ch c th c c (nu th khi vo cc bin s to
mt bin cc b mi trong phm vi trong vng, v khng nh hng ti bin cng tn
phm vi ngoi).
9. Lp http://www.vithon.org/tutorial/2.5/node11.html
2 of 13 08/31/2011 10:27 AM
Thng thng, phm vi ni b tham chiu cc tn ni b ca hm hin ti (da vo
vn bn). Bn ngoi hm, phm vi ni b tham chiu cng mt vng tn nh phm vi
ton cc: vng tn ca m-un. Cc nh ngha lp t thm mt vng tn khc
trong phm vi ni b.
im quan trng cn ghi nh l phm vi c xc nh theo vn bn: phm vi ton
cc ca mt hm c nh ngha trong mt m-un l vng tn ca m-un , cho
d m-un c gi t u, hoc c t tn lng no. Mt khc, vic tm tn
c thc hin lc chy -- tuy nhin, nh ngha ngn ng ang pht trin theo hng
xc nh tn vo lc ``dch'', cho nn ng da vo vic tm tn ng! (Thc ra th
cc bin ni b c xc nh tnh.)
Mt im ng ca Python l cc php gn lun gn vo phm vi trong cng. Php
gn khng chp d liu -- ch ch buc cc tn v cc i tng. Xa cng vy: cu
lnh "del x" b rng buc x khi vng tn c tham chiu ti bi phm vi ni b.
Thc t l mi tc v c thm cc tn mi u dng phm vi ni b: in hnh l cc
cu lnh nhp v cc nh ngha hm buc tn m-un hoc tn hm vo phm vi ni
b. (Lnh global c th c dng cho bit mt bin c th l phm vi ton cc.)
9.3 Ci nhn u tin v lp
Lp thm mt t c php mi, ba kiu i tng mi, v mt t ng ngha mi.
9.3.1 C php nh ngha lp
Kiu n gin nht ca vic nh ngha lp nhn ging nh:
class ClassName:
<statement-1>
.
.
.
<statement-N>
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).
9. Lp http://www.vithon.org/tutorial/2.5/node11.html
3 of 13 08/31/2011 10:27 AM
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'
th MyClass.i v MyClass.f l nhng tham chiu thuc tnh hp l, tr v mt s
nguyn v mt i tng hm, theo th t . Cc thuc tnh lp cng c th gn vo,
cho nn bn c th thay i gi tr ca MyClass.i bng php gn. __doc__ cng l
mt thuc tnh hp l, tr v chui ti liu ca lp: "A simple example class".
Class instantiation (to trng hp lp) dng cng cch vit nh gi hm. Hy tng
tng mt i tng lp l mt hm khng thng s tr v mt trng hp ca lp. V
d (vi lp trn):
x = MyClass()
to mt trng hp mi ca lp v gn i tng ny vo bin ni b x.
Tc v to trng hp (``gi'' mt i tng lp) to mt i tng rng. Nhiu lp
thch to i tng vi cc trng hp c khi to mt trng thi u no . Do
mt lp c th nh ngha mt phng thc c bit tn __init__(), nh sau:
def __init__(self):
self.data = []
Khi mt lp nh ngha mt phng thc __init__() , vic to trng hp lp s t
ng gi __init__() trng hp lp mi va c to. Trong v d ny, mt trng
hp khi to mi c th c ti ra t:
x = MyClass()
D nhin, __init__() (phng thc) c th nhn thm thng s. Trong trng hp ,
cc thng s a vo php to trng hp lp s c truyn vo __init__(). V d,
>>> class Complex:
... def __init__(self, realpart, imagpart):
... self.r = realpart
... self.i = imagpart
...
>>> x = Complex(3.0, -4.5)
>>> x.r, x.i
(3.0, -4.5)
9.3.3 i tng trng hp
9. Lp http://www.vithon.org/tutorial/2.5/node11.html
4 of 13 08/31/2011 10:27 AM
Chng ta c th lm c g vi nhng i tng trng hp? Tc v duy nht m cc
i tng trng hp hiu c l tham chiu thuc tnh. C hai loi tn thuc tnh
hp l, thuc tnh d liu v phng thc.
data attributes (thuc tnh d liu lp) tng ng vi ``bin trng hp'' trong
Smalltalk, v ''thnh vin d liu'' trong C++. Thuc tnh d liu khng cn c khai
bo; nh cc bin ni b, chng t ng tn ti khi c gn vo. V d, nu x l mt
trng hp ca MyClass c to ra trn, on m sau in ra gi tr 16, m khng
cha li du vt:
x.counter = 1
while x.counter < 10:
x.counter = x.counter * 2
print x.counter
del x.counter
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.
9.3.4 i tng phng thc
Thng thng, mt phng thc c gi ngay sau khi n b buc:
x.f()
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()
s tip tc in "hello world" mi mi.
Chuyn g tht s xy ra khi mt phng thc c gi? Bn c th nhn ra rng
x.f() c gi vi khng thng s, mc d nh ngha hm ca f ch nh mt thng
s. Chuyn g xy ra vi thng s ? Python chc chn nng mt bit l khi mt hm
cn mt thng s c gi sung -- cho d thng s c c dng hay khng i
na...
Tht ra, bn cng c th on ra c cu tr li: im c bit ca phng thc
9. Lp http://www.vithon.org/tutorial/2.5/node11.html
5 of 13 08/31/2011 10:27 AM
l i tng c truyn vo thng s u tin ca hm. Trong v d ca chng
ta, li gi x.f() hon ton tng ng vi MyClass.f(x). Ni chung, gi mt hm
vi mt danh sch n thng s th tng ng vi vic gi hm tng ng vi mt
danh sch thng s c to ra bng cch chn i tng ca phng thc vo trc
thng s th nht.
(Hiu n gin l obj.name(arg1, arg2) tng ng vi Class.name(obj, arg1,
arg2) trong obj l i tng trng hp ca lp Class, name l mt thuc tnh hp
l khng phi d liu, tc l i tng hm ca lp .)
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:
9. Lp http://www.vithon.org/tutorial/2.5/node11.html
6 of 13 08/31/2011 10:27 AM
f = f1
def g(self):
return 'hello world'
h = g
By gi f, g v h u l thuc tnh ca lp C m tham chiu ti cc i tng hm, v
do chng u l phng thc ca cc trng hp ca C -- h hon ton tng ng
vi g. Ch rng kiu vit ny thng ch lm ngi c cng thm kh hiu m thi.
Phng thc c th gi phng thc khc thng qua thuc tnh phng thc ca
thng s self :
class Bag:
def __init__(self):
self.data = []
def add(self, x):
self.data.append(x)
def addtwice(self, x):
self.add(x)
self.add(x)
Phng thc c th tham chiu ti cc tn ton cc theo cng mt cch nh cc hm
thng thng. Phm vi ton cc ca mt phng thc l m-un cha nh ngha lp.
(Phm vi ton cc khng bao gi l lp!) Trong khi bn t gp vic s dng d liu
ton cc trong mt phng thc, c nhng cch dng hon ton chnh ng: v d
nh hm v m-un c nhp vo phm vi ton cc c th c s dng bi phng
thc, cng nh hm v lp c nh ngha trong . Thng thng, lp cha cc
phng thc ny c nh ngha ngay trong phm vi ton cc, v trong phn k y
chng ta s thy ti sao mt phng thc mun tham chiu ti chnh lp ca n!
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>
Tn BaseClassName phi c nh ngha trong mt phm vi cha nh ngha lp
con. Thay v tn lp c s, cc biu thc khc cng c cho php. iu ny rt hu
ch, v d, khi m lp c s c nh ngha trong mt m-un khc:
class DerivedClassName(modname.BaseClassName):
Vic thc thi nh ngha lp con tin hnh nh l lp c s. Khi mt i tng lp c
to ra, lp c s s c nh. N c dng trong vic gii cc tham chiu thuc tnh:
nu mt thuc tnh khng c tm thy trong lp, vic tm kim s tip tc lp c
s. Lut ny s c lp li nu lp c s k tha t mt lp khc.
Khng c g c bit trong vic to trng hp ca cc lp con: DerivedClassName()
9. Lp http://www.vithon.org/tutorial/2.5/node11.html
7 of 13 08/31/2011 10:27 AM
to mt trng hp ca lp. Cc tham chiu hm c gii nh sau: thuc tnh lp
tng ng s c tm, i xung chui cc lp c s nu cn, v tham chiu phng
thc l hp l nu tm thy mt i tng hm.
Lp con c th nh ngha li cc phng thc ca lp c s. Bi v phng thc khng
c quyn g c bit khi gi mt phng thc ca cng mt i tng, mt phng
thc ca lp c s gi mt phng thc khc c nh ngha trong cng lp c s c
th l ang gi mt phng thc do lp con nh ngha li. (Ngi dng C++ c
th hiu l mi phng thc ca Python l virtual.)
Mt phng thc c nh ngha li trong lp con c th mun m rng thay v thay
th phng thc cng tn ca lp c s. C mt cch n gin gi phng thc ca
lp s s: ch vic gi "BaseClassName.methodname(self, arguments)". i khi iu
ny cng c ch cho ngi dng. (Lu rng on m ch hot ng nu lp c s
c nh ngha hoc nhp trc tip vo phm vi ton cc.)
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.
9.6 Bin ring
C mt dng h tr nho nh nho cc t nh danh ring ca lp (class-private
identier). Cc t nh danh c dng __spam (t nht hai du gch di u, nhiu
9. Lp http://www.vithon.org/tutorial/2.5/node11.html
8 of 13 08/31/2011 10:27 AM
nht mt du dch di cui) c thay th vn bn (textually replace) bng
_classname__spam, trong classname l tn lp hin ti vi cc gch di u ct
b. Vic xo trn tn (mangling) c thc hin m khng quan tm ti v tr c php
ca nh danh, cho nn n c th c dng nh ngha cc trng hp, bin,
phng thc, ring ca lp, hoc cc bin ton cc, v ngay c cc bin ca trng
hp, ring vi lp ny trn nhng trng hp ca lp khc . Nu tn b xo trn di
hn 255 k t th n s b ct i. Bn ngoi lp, hoc khi tn lp ch c k t gch
di, vic xo trn tn s khng xy ra.
Xo trn tn nhm cung cp cho cc lp mt cch nh ngha d dng cc bin v
phng thc ``ring'', m khng phi lo v cc bin trng hp c nh ngha bi
lp con, hoc vic s dng bin trng hp bi m bn ngoi lp. Lu rng vic xo
trn tn c thit k ch yu trnh trng lp; ngi quyt tm vn c th truy cp
hoc thay i bin ring. V iu ny cng c th c ch trong cc trng hp c bit,
nh trong trnh g ri, v l mt l do ti sao l hng ny vn cha c v.
Lu rng m truyn vo exec, eval() hoc execfile() khng nhn tn lp ca lp
gi l tn lp hin ti; iu ny cng ging nh tc dng ca cu lnh global , tc
dng ca n cng b gii hn m c bin dch cng. Cng gii hn ny cng c
p dng vo getattr(), setattr() v delattr(), khi tham chiu __dict__ trc tip.
9.7 Nhng iu khc
i khi n tht l hu ch khi c mt kiu d liu ging nh Pascal ``record'' hoc C
``struct'', gi gn vi mu d liu vo chung vi nhau. Mt nh ngha lp rng thc
hin c vic ny:
class Employee:
pass
john = Employee() # Create an empty employee record
# Fill the fields of the record
john.name = 'John Doe'
john.dept = 'computer lab'
john.salary = 1000
Vi m Python cn mt kiu d liu tru tng, ta c th thay vo mt lp gi lp
cc phng thc ca kiu d liu . V d, nu bn c mt hm nh dng mt vi d
liu trong mt i tng tp tin, bn c th nh ngha mt lp vi cc phng thc
read() v readline() ly d liu t mt chui, v truyn vo n mt thng s.
Cc i tng phng trc trng hp cng c thuc tnh: m.im_self l mt i tng
trng hp vi phng thc m, v m.im_func l i tng hm tng ng vi phng
thc.
9.8 Bit l cng l lp
Cc bit l c nh ngha bi ngi dng cng c nh danh theo lp. Bng cch
ny, mt h thng phn cp bit l c th c to ra.
C hai dng lnh raise mi:
9. Lp http://www.vithon.org/tutorial/2.5/node11.html
9 of 13 08/31/2011 10:27 AM
raise Class, instance
raise instance
Trong dng u, instance phi l mt trng hp ca kiu Class hoc l lp con ca
n. Dng th hai l rt gn ca:
raise instance.__class__, instance
Lp trong v except tng thch vi mt bit l nu n cng lp, hoc l mt lp c s
(nhng chiu ngc li th khng ng -- mt v except dng lp con s khng tng
thch vi mt bit l lp c s). V d, on m sau s in B, C, D theo th t :
class B:
pass
class C(B):
pass
class D(C):
pass
for c in [B, C, D]:
try:
raise c()
except D:
print "D"
except C:
print "C"
except B:
print "B"
Nu cc v except c t ngc (vi "except B" u), n s in B, B, B -- v except
ph hp u tin c thc thi.
Khi mt thng ip li c in, tn lp ca bit l c in, theo sau bi du hai chm
v mt khong trng, v cui cng l trng hp c chuyn thnh chui bng
hm c sn str().
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
9. Lp http://www.vithon.org/tutorial/2.5/node11.html
10 of 13 08/31/2011 10:27 AM
v hp nht Python. ng sau mn nhung, cu lnh for gi iter() trn i tng
cha. Hm ny tr v mt i tng b lp c nh ngha phng thc next() truy
xut v cc phn t trong b cha (container). Khi khng cn phn t no, next()
nng bit l StopIteration yu cu vng lp for kt thc. V d sau cho thy cch
hot ng:
>>> s = 'abc'
>>> it = iter(s)
>>> it
<iterator object at 0x00A1DB50>
>>> it.next()
'a'
>>> it.next()
'b'
>>> it.next()
'c'
>>> it.next()
Traceback (most recent call last):
File "<stdin>", line 1, in ?
it.next()
StopIteration
Chng ta hiu giao thc b lp, nn chng ta c th thm cch thc b lp
(iterator behavior) vo lp ca chng ta mt cch d dng. nh ngha mt phng
thc __iter__() tr v mt i tng vi mt phng thc next() . Nu lp c nh
ngha next(), th __iter__() ch cn tr v self:
class Reverse:
"Iterator for looping over a sequence backwards"
def __init__(self, data):
self.data = data
self.index = len(data)
def __iter__(self):
return self
def next(self):
if self.index == 0:
raise StopIteration
self.index = self.index - 1
return self.data[self.index]
>>> for char in Reverse('spam'):
... print char
...
m
a
p
s
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
9. Lp http://www.vithon.org/tutorial/2.5/node11.html
11 of 13 08/31/2011 10:27 AM
mi d liu v cu lnh c thc thi ln cui). Mt v d cho thy b sinh c th
c to ra rt d dng:
def reverse(data):
for index in range(len(data)-1, -1, -1):
yield data[index]
>>> for char in reverse('golf'):
... print char
...
f
l
o
g
Bt k vic g c th c thc hin vi b sinh cng c th c thc hin vi cc b
lp da trn lp nh bn n phn trc. iu khin b sinh nh gn l cc
phng thc __iter__() v next() c t ng to ra.
Mt tnh nng chnh khc l cc bin ni b v trng thi thc thi c t ng lu
gia cc ln gi. iu ny lm cho hm d vit hn v r rng hn l cch s dng
bin trng hp nh self.index v self.data.
Thm vo vic t ng to v lu trng thi chng trnh, khi cc b to kt thc,
chng t ng nng StopIteration. Cng li, cc tnh nng ny lm cho vic to cc
b lp khng c g kh hn l vit mt hm bnh thng.
9.11 Biu thc b to
Mt vi b sinh n gin c th c vit mt cch xc tch nh cc biu thc bng
cch dng mt c php ging nh gp danh sch (list comprehension) nhng vi
ngoc trn thay v ngoc vung. Cc biu thc ny c thit k cho nhng khi b
sinh c s dng ngay lp tc bi hm cha n. Biu thc b sinh gn hn nhng t
kh chuyn hn l cc nh ngha b sinh y v thng chim t b nh hn l gp
danh sch tng ng.
V d:
>>> sum(i*i for i in range(10)) # sum of squares
285
>>> xvec = [10, 20, 30]
>>> yvec = [7, 5, 3]
>>> sum(x*y for x,y in zip(xvec, yvec)) # dot product
260
>>> from math import pi, sin
>>> sine_table = dict((x, sin(x*pi/180)) for x in range(0, 91))
>>> unique_words = set(word for line in page for word in line.split())
>>> valedictorian = max((student.gpa, student.name) for student in graduates)
>>> data = 'golf'
9. Lp http://www.vithon.org/tutorial/2.5/node11.html
12 of 13 08/31/2011 10:27 AM
>>> 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.
9. Lp http://www.vithon.org/tutorial/2.5/node11.html
13 of 13 08/31/2011 10:27 AM
Bi ch dn Python
10. Gii thiu s v b th vin chun
10.1 Giao tip vi h thng
os (m-un) cung cp hng lot cc hm dng cho vic giao tip vi h iu hnh:
>>> import os
>>> os.system('time 0:02')
0
>>> os.getcwd() # Return the current working directory
'C:\\Python24'
>>> os.chdir('/server/accesslogs')
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>
i vi cc cng vic qun l le v th mc thng thng, m-un shutil cung cp
mt giao din mc cao hn v d dng hn:
>>> import shutil
>>> shutil.copyfile('data.db', 'archive.db')
>>> shutil.move('/build/executables', 'installdir')
10.2 K t thay th tp tin
glob (m-un) cng h tr vic to danh sch cc tp tin t vic tm kim th mc dng
k t thay th (wildcard):
>>> import glob
>>> glob.glob('*.py')
['primes.py', 'random.py', 'quote.py']
10.3 Thng s dng lnh
Cc kch bn ph dng thng phi x l cc tham s dng lnh. Cc tham s ny c
lu thnh mt danh sch m-un sys trong thuc tnh argv . V d, kt qu sau y thu
c t vic chy lnh "python demo.py one two three" t dng lnh:
>>> import sys
10. Gii thiu s v b th vin chun http://www.vithon.org/tutorial/2.5/node12.html
1 of 5 08/31/2011 10:28 AM
>>> print sys.argv
['demo.py', 'one', 'two', 'three']
getopt (m-un) x l sys.argv theo cc nguyn tc ca hm UNIX getopt() . Nu cn
cc thao tc linh hot v hu hiu hn, chng ta c th dng m-un optparse .
10.4 Chuyn hng lung ra v kt thc
chng trnh
sys (m-un) cng c cc thuc tnh cho stdin, stdout, v stderr. Ci cui rt hu dng
trong vic sinh ra cc cnh bo v thng bo li v vic hin th chng ngay c khi stdout
c nh hng li:
>>> sys.stderr.write('Warning, log file not found starting a new one\n')
Warning, log file not found starting a new one
Cch thot khi mt kch bn mt cch trc tip nht l dng "sys.exit()".
10.5 Khp mu chui
re (m-un) cung cp cc cng c biu thc chnh quy dng cho vic x l chui mc
cao. Biu thc chnh quy cung cp cc phng n sc tch v ti u cho cc thao tc tm
kim v x l chui phc tp:
>>> import re
>>> re.findall(r'\bf[a-z]*', 'which foot or hand fell fastest')
['foot', 'fell', 'fastest']
>>> re.sub(r'(\b[a-z]+) \1', r'\1', 'cat in the the hat')
'cat in the hat'
i vi cc chc nng x l chui c bn th cc phng thc ca i tng chui c
a chung hn bi chng d c v d g ri hn:
>>> 'tea for too'.replace('too', 'two')
'tea for two'
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
random (m-un) h tr vic to ra cc la chn ngu nhin:
>>> import random
>>> random.choice(['apple', 'pear', 'banana'])
'apple'
>>> random.sample(xrange(100), 10) # sampling without replacement
[30, 83, 16, 4, 8, 81, 41, 50, 18, 33]
10. Gii thiu s v b th vin chun http://www.vithon.org/tutorial/2.5/node12.html
2 of 5 08/31/2011 10:28 AM
>>> random.random() # random float
0.17970987693706186
>>> random.randrange(6) # random integer chosen from range(6)
4
10.7 Truy cp internet
Python cung cp mt vi m-un khc nhau cho vic truy cp internet v x l cc giao
thc internet. Hai m-un n gin nht l urllib2 dnh cho vic thu thp d liu t
cc URL v smtplib dnh cho vic gi th in t:
>>> import urllib2
>>> for line in urllib2.urlopen('http://tycho.usno.navy.mil/cgi-bin/timer.pl'):
... if 'EST' in line or 'EDT' in line: # look for Eastern Time
... print line

<BR>Nov. 25, 09:43:32 PM EST
>>> import smtplib
>>> server = smtplib.SMTP('localhost')
>>> server.sendmail('soothsayer@example.org', 'jcaesar@example.org',
"""To: jcaesar@example.org
From: soothsayer@example.org
Beware the Ides of March.
""")
>>> server.quit()
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
10. Gii thiu s v b th vin chun http://www.vithon.org/tutorial/2.5/node12.html
3 of 5 08/31/2011 10:28 AM
bin nh: zlib, gzip, bz2, zipfile, v tarfile.
>>> import zlib
>>> s = 'witch which has which witches wrist watch'
>>> len(s)
41
>>> t = zlib.compress(s)
>>> len(t)
37
>>> zlib.decompress(t)
'witch which has which witches wrist watch'
>>> zlib.crc32(s)
226805979
10.10 o lng hiu sut
Mt vi ngi dng Python rt quan tm n vic tm hiu s khc bt v hiu nng gia
cc phng n khc nhau ca cng mt vn . Python cung cp mt cng c o c
tha mn nhu cu ny.
V d, chng ta thng mun s dng tnh nng gi b v m gi b thay cho phng
php thng thng trong vic hon i tham s. M-un timeit cho thy phng php
ny c hiu nng nhnh hn phng php thng thng:
>>> from timeit import Timer
>>> Timer('t=a; a=b; b=t', 'a=1; b=2').timeit()
0.57535828626024577
>>> Timer('a,b = b,a', 'a=1; b=2').timeit()
0.54962537085770791
So snh vi phn bit v thi gian v s chnh xc cao ca timeit, cc m-un
profile v pstats cung cp cc cng c cho vic xc nh cc on m tiu tn nhiu
thi gian trong cc khi m ln hn.
10.11 Qun l cht lng
Mt phng php pht trin phn mm cht lng cao l vit cc hm kim tra cho
tng hm khi vit cc hm v chy cc hm kim tra mt cch thng xuyn trong qu
trnh pht trin phn mm.
doctest (m-un) cung cp cng c cho vic r sot mt m-un v thm nh cc hm
kim tra nhng trong ti liu ca chng trnh. Vic xy dng cc on kim tra c
thc hin n gin bng cch ct v dn mt on gi hm thng thng km theo kt
qu ca hm vo ti liu chng trnh. Vic ny ci thin ng k ti liu chng
trnh bi n cung cp cho ngi dng mt v d v vic s dng hm v cho php
m-un doctest kim tra tnh ng n ca hm ny so vi ti liu:
def average(values):
"""Computes the arithmetic mean of a list of numbers.
>>> print average([20, 30, 70])
40.0
"""
return sum(values, 0.0) / len(values)
10. Gii thiu s v b th vin chun http://www.vithon.org/tutorial/2.5/node12.html
4 of 5 08/31/2011 10:28 AM
import doctest
doctest.testmod() # automatically validate the embedded tests
unittest (m-un) khng d dng nh m-un doctest , nhng n h tr cc hm kim
tra ton din hn v lu gi chng trong mt tp tin ring bit:
import unittest
class TestStatisticalFunctions(unittest.TestCase):
def test_average(self):
self.assertEqual(average([20, 30, 70]), 40.0)
self.assertEqual(round(average([1, 5, 7]), 1), 4.3)
self.assertRaises(ZeroDivisionError, average, [])
self.assertRaises(TypeError, average, 20, 30, 70)
unittest.main() # Calling from the command line invokes all tests
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.
10. Gii thiu s v b th vin chun http://www.vithon.org/tutorial/2.5/node12.html
5 of 5 08/31/2011 10:28 AM
Bi ch dn Python
11. Gii thiu s v b th vin chun -
Phn II
Bi gii thiu th hai ny ni v cc m-un chuyn su nhm p ng cc tc v lp
trnh chuyn nghip. Cc m-un ny t khi xut hin cc kch bn nh.
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', ...])"
pprint (m-un) h tr vic kim sot vic in cc i tng sn c hoc cc i tng
do ngi dng nh ngha mt cch tinh vi hn theo mt phng thc m rnh thng
dch c th hiu c. Khi kt qu hin th ngn hn mt dng th "pretty printer" s
thm cc du xung dng v du tht vo u dng khin cho cu trc d liu c th
hin r rt hn:
>>> import pprint
>>> t = [[[['black', 'cyan'], 'white', ['green', 'red']], [['magenta',
... 'yellow'], 'blue']]]
...
>>> pprint.pprint(t, width=30)
[[[['black', 'cyan'],
'white',
['green', 'red']],
[['magenta', 'yellow'],
'blue']]]
textwrap (m-un) nh dng on vn bn sao cho va vi rng ca mn hnh:
>>> import textwrap
>>> doc = """The wrap() method is just like fill() except that it returns
... a list of strings instead of one big string with newlines to separate
... the wrapped lines."""
...
>>> print textwrap.fill(doc, width=40)
The wrap() method is just like fill()
except that it returns a list of strings
instead of one big string with newlines
to separate the wrapped lines.
locale (m-un) s dng mt c s d liu cc nh dng d liu da trn c im ca
tng khu vc. Hm nh dng ca locale c thuc tnh to nhm, cho php nh dng
trc tip cc con s vi cc du phn chia nhm:
>>> import locale
11. Gii thiu s v b th vin chun - Phn II http://www.vithon.org/tutorial/2.5/node13.html
1 of 7 08/31/2011 10:30 AM
>>> locale.setlocale(locale.LC_ALL, 'English_United States.1252')
'English_United States.1252'
>>> conv = locale.localeconv() # get a mapping of conventions
>>> x = 1234567.8
>>> locale.format("%d", x, grouping=True)
'1,234,567'
>>> locale.format("%s%.*f", (conv['currency_symbol'],
... conv['frac_digits'], x), grouping=True)
'$1,234,567.80'
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.'
substitute (phng thc) nng KeyError nu bin gi ch khng c cung cp bi
mt t in hay mt tham s nhp t bn phm. i vi cc trnh ng dng kiu nhp
liu vo th in t, d liu nhp bi ngi dng c th c thiu st, khi phng thc
safe_substitute s thch hp hn -- n gi nguyn cc bin gi ch nu d liu b thiu:
>>> t = Template('Return the $item to $owner.')
>>> d = dict(item='unladen swallow')
>>> t.substitute(d)
Traceback (most recent call last):
. . .
KeyError: 'owner'
>>> t.safe_substitute(d)
'Return the unladen swallow to $owner.'
Cc lp con ca Template c th nh ngha mt phn t phn chia ty bin. V d mt
ng dng i tn nh hng lot ca mt trnh duyt nh c th s dng du phn trm
lm cc bin gi ch ngy thng, s th t nh, hay nh dng nh:
>>> import time, os.path
>>> photofiles = ['img_1074.jpg', 'img_1076.jpg', 'img_1077.jpg']
>>> class BatchRename(Template):
... delimiter = '%'
>>> fmt = raw_input('Enter rename style (%d-date %n-seqnum %f-format): ')
Enter rename style (%d-date %n-seqnum %f-format): Ashley_%n%f
>>> t = BatchRename(fmt)
>>> date = time.strftime('%d%b%y')
>>> for i, filename in enumerate(photofiles):
... base, ext = os.path.splitext(filename)
11. Gii thiu s v b th vin chun - Phn II http://www.vithon.org/tutorial/2.5/node13.html
2 of 7 08/31/2011 10:30 AM
... newname = t.substitute(d=date, n=i, f=ext)
... print '%s --> %s' % (filename, newname)
img_1074.jpg --> Ashley_0.jpg
img_1076.jpg --> Ashley_1.jpg
img_1077.jpg --> Ashley_2.jpg
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.3 Lm vic vi bn ghi d liu nh phn
struct (m-un) cung cp cc hm pack() v unpack() dng vi cc nh dng bn
ghi nh phn vi chiu di khng c nh. V d sau y minh ha phng php lp qua
cc thng tin trong phn tiu ca mt tp tin ZIP (k hiu "H" v "L" biu din cc s
khng du hai byte v bn byte):
import struct
data = open('myfile.zip', 'rb').read()
start = 0
for i in range(3): # show the first 3 file headers
start += 14
fields = struct.unpack('LLLHH', data[start:start+16])
crc32, comp_size, uncomp_size, filenamesize, extra_size = fields
start += 16
filename = data[start:start+filenamesize]
start += filenamesize
extra = data[start:start+extra_size]
print filename, hex(crc32), comp_size, uncomp_size
start += extra_size + comp_size # skip to the next header
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
11. Gii thiu s v b th vin chun - Phn II http://www.vithon.org/tutorial/2.5/node13.html
3 of 7 08/31/2011 10:30 AM
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.'
Kh khn ln nht ca cc chng trnh ng dng a lung l vic iu phi cc lung
phi chia s d liu hay cc ti nguyn khc. V mt ny, m-un threading h tr mt
s hm ng b s cp nh cc kha (lock), cc s kin (event), cc bin iu kin
(condition) v cc c hiu (semaphore).
Mc d cc cng c k trn rt mnh, nhung nhng li thit k nh c th dn ti cc vn
rt kh c th ti to c. Do , phng php c a chung trong vic iu phi
cc tc v l tp hp cc truy cp ti mt ti nguyn vo mt lung, sau s dng
m-un Queue np cc yu cu t cc lung khc ti lung . Cc trnh ng dng s
dng i tng Queue cho vic giao tip v iu phi gia cc lung c u im l d
thit k hn, d c hn v ng tin cy hn.
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')
on m trn s cho kt qu sau:
WARNING:root:Warning:config file server.conf not found
ERROR:root:Error occurred
CRITICAL:root: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.
11.6 Tham chiu yu
11. Gii thiu s v b th vin chun - Phn II http://www.vithon.org/tutorial/2.5/node13.html
4 of 7 08/31/2011 10:30 AM
Python h tr vic qun l b nh mt cch t ng (bao gm vic m tham chiu vi
hu ht cc i tng v vic thu dn rc). Vng nh c gii phng nhanh chng sau
khi tham chiu cui cng n n kt thc.
Phng php ny t ra hiu qu vi hu ht cc trnh ng dng s dng Python, tuy vy
i khi ta c nhu cu theo di mt i tng chng no chng c s dng mt ch
khc. Tuy vy vic theo di ny li to ra mt tham chiu n i tng , khin bn
thn n tr thnh mt tham chiu vnh vin. M-un weakref cho php theo di mt i
tng m khng cn phi to mt tham chiu ti i tng . Khi i tng khng cn
cn dng na, n s t ng b loi ra khi bng tham chiu yu v mt hm gi ngc
(callback) s c gi ti i tng weakref. Cc ng dng ph bin c cha cc i
tng c lu tm v i hi chi ph khi to cao:
>>> import weakref, gc
>>> class A:
... def __init__(self, value):
... self.value = value
... def __repr__(self):
... return str(self.value)
...
>>> a = A(10) # create a reference
>>> d = weakref.WeakValueDictionary()
>>> d['primary'] = a # does not create a reference
>>> d['primary'] # fetch the object if it is still alive
10
>>> del a # remove the one reference
>>> gc.collect() # run garbage collection right away
0
>>> d['primary'] # entry was automatically removed
Traceback (most recent call last):
File "<pyshell#108>", line 1, in -toplevel-
d['primary'] # entry was automatically removed
File "C:/PY24/lib/weakref.py", line 46, in __getitem__
o = self.data[key]()
KeyError: 'primary'
11.7 Cng c lm vic vi danh sch
Kiu danh sch sn c ca Python c th p ng c nhu cu v nhiu kiu cu trc d
liu khc nhau. Tuy vy chng ta i khi cn ti cc kiu cu trc khc, ty thuc vo
cc mc tiu c th v hiu nng.
array (m-un) cung cp i tng array() ging nh mt danh sch cha cc d liu
cng kiu v lu gi chng gn hn. V d sau cho thy mt mng cc con s c lu
gi di dng cc s khng du hai byte (m "H") thay v mi phn t chim 16 byte nh
trong mt danh sch thng thng cha cc i tng s nguyn ca Python:
>>> from array import array
>>> a = array('H', [4000, 10, 700, 22222])
>>> sum(a)
26932
>>> a[1:3]
array('H', [10, 700])
collections (m-un) cung cp i tng deque() ging nh mt danh sch nhng c
11. Gii thiu s v b th vin chun - Phn II http://www.vithon.org/tutorial/2.5/node13.html
5 of 7 08/31/2011 10:30 AM
cc thao tc thm vo v ly ra u bn tri nhanh hn, nhng vic tm kim gia th
li chm hn. Cc i tng ny thch hp cho vic ci t cc hng i v tm kim cy
theo chiu rng:
>>> from collections import deque
>>> d = deque(["task1", "task2", "task3"])
>>> d.append("task4")
>>> print "Handling", d.popleft()
Handling task1
unsearched = deque([starting_node])
def breadth_first_search(unsearched):
node = unsearched.popleft()
for m in gen_moves(node):
if is_goal(m):
return m
unsearched.append(m)
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')]
heapq (m-un) cung cp cc hm ci t ng (heap) da trn cc danh sch thng
thng. Phn t c gi tr thp nht lun c gi v tr u tin. Hm ny rt c ch
trong cc trnh ng dng i hi vic truy cp ti phn t nh nht m khng cn phi
sp xp li ton b danh sch:
>>> from heapq import heapify, heappop, heappush
>>> data = [1, 3, 5, 7, 9, 2, 4, 6, 8, 0]
>>> heapify(data) # rearrange the list into heap order
>>> heappush(data, -5) # add a new entry
>>> [heappop(data) for i in range(3)] # fetch the three smallest entries
[-5, 0, 1]
11.8 S hc du chm ng thp phn
decimal (m-un) cung cp kiu d liu Decimal cho cc php ton du chm ng h
thp phn. So vi cu trc du chm ng nh phn float sn c ca Python, lp ny rt
c ch trong cc trnh ng dng v ti chnh v cc cng vic i hi vic biu din
chnh xc cc s thp phn, kim sot mc chnh xc cng nh vic lm trn cc con
s theo cc quy nh ra, theo di v tr ca du chm ng hay trong cc trnh ng
dng m ngi s dng mong mun thu c kt qu khp vi kt qu tnh ton bng
tay.
V d nh, vic tnh 5% thu trn mt cuc gi in gi 70 cent s cho kt qu khc
nhau nu s dng cc php ton dy chm ng h thp phn v nh phn. S khc bit
tr nn r rt nu kt qu c lm trn ti cent:
>>> from decimal import *
>>> Decimal('0.70') * Decimal('1.05')
11. Gii thiu s v b th vin chun - Phn II http://www.vithon.org/tutorial/2.5/node13.html
6 of 7 08/31/2011 10:30 AM
Decimal("0.7350")
>>> .70 * 1.05
0.73499999999999999
Decimal gi mt s khng v tr cui cng, n t ng quy kt qu kiu c bn ch s
sau du chm nu cc tha s ca php nhn c hai ch s sau du chm. Decimal thc
hin cc php ton tng t nh cch chng c tnh bng tay, nh trnh c cc
vn gp phi khi du chm ng h nh phn khng th biu din chnh xc cc gi tr
thp phn.
Vic biu din chnh xc cc con s gip cho lp Decimal c th thc hin c cc php
tnh modulo v cc so snh bng, iu m du chm ng h nh phn khng lm c:
>>> Decimal('1.00') % Decimal('.10')
Decimal("0.00")
>>> 1.00 % 0.10
0.09999999999999995

>>> sum([Decimal('0.1')]*10) == Decimal('1.0')
True
>>> sum([0.1]*10) == 1.0
False
decimal (m-un) cung cp cc php ton vi chnh xc cao, ty thuc vo i hi
ca ngi dng:
>>> getcontext().prec = 36
>>> Decimal(1) / Decimal(7)
Decimal("0.142857142857142857142857142857142857")
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. Gii thiu s v b th vin chun - Phn II http://www.vithon.org/tutorial/2.5/node13.html
7 of 7 08/31/2011 10:30 AM
Bi ch dn Python
12. Tip theo?
c xong bi ch dn ny c l lm tng thm s thch th ca bn vi
ngn ng Python -- v bn cng mun nhanh chng p dng Python gii
quyt cc vn trong i sng. Th by gi bn nn hc tip t u?
Bi ch dn ny l mt phn ca b ti liu ca Python. Nhng ti liu khc
trong b ny gm:
Tham kho th vin Python:
Bn nn duyt qua cm nang ny v n cung cp ti liu tham kho y
(d l ngn gn) v cc kiu, hm, v cc m-un trong b th vin
chun. B phn phi Python chun c rt nhiu m b sung. C nhng
m-un c hp th UNIX , ly ti liu t HTTP, sinh s ngu nhin,
phn tch thng s dng lnh, vit cc ng dng CGI, nn d liu, v rt
nhiu tc v khc. Lt qua Tham kho th vin s cho bn bit nhng g
ang c.
Ci t cc m-un Python gii thch lm th no ci cc m-un
ngoi c vit bi cc ngi dng Python khc.
Tham kho ngn ng: Mt ti liu chi tit v c php v ng ngha ca
Python. Kh c, nhng rt hu dng v n l hng dn y ca chnh
ngn ng.
Cc ti nguyn Python khc:
http://www.python.org: Trang mng Python chnh. N c m, ti liu, v
ch dn ti cc trang lin quan ti Python trn mng. Trang ny c
chp ra khp ni trn th gii nh Chu u, Nht, v c; cc bn sao
c th nhanh hn l trang chnh, ty thuc vo v tr a l ca bn.
http://docs.python.org: Truy cp nhanh ti ti liu Python.
http://cheeseshop.python.org: Ch mc gi Python (Python Package
Index), tn lng l Ca hng Ph-mai (Cheese Shop), l mt ch mc ca
cc m-un Python do ngi dng to ti v. Mt khi bn bt u tung
m ca bn ra ngoi, bn c th ng k n y ngi khc c th
tm thy n.
http://aspn.activestate.com/ASPN/Python/Cookbook/: Sch dy nu n
Python (Python Cookbook) l mt tp hp ln cc m mu, cc m-un
ln hn, v cc kch bn hu dng. Cc ng gp quan trng c thu
thp vo mt quyn sch tn l Python Cookbook (O'Reilly & Associates,
12. Tip theo? http://www.vithon.org/tutorial/2.5/node14.html
1 of 2 08/31/2011 10:50 AM
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 python-
list@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.
12. Tip theo? http://www.vithon.org/tutorial/2.5/node14.html
2 of 2 08/31/2011 10:50 AM
Python Tutorial
This Appendix was left untranslated.
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 avors 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 eect.
A.2 History Substitution
History substitution works as follows. All non-empty input lines issued are saved
in a history buer, and when a new prompt is given you are positioned on a new
line at the bottom of this buer. C-P moves one line up (back) in the history buer,
C-N moves one down. Any line in the history buer can be edited; an asterisk
appears in front of the prompt to mark a line as modied. 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
A. Interactive Input Editing and History Substitution http://www.vithon.org/tutorial/2.5/node15.html
1 of 4 08/31/2011 10:51 AM
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
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 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
import rlcompleter, readline
readline.parse_and_bind('tab: complete')
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
A. Interactive Input Editing and History Substitution http://www.vithon.org/tutorial/2.5/node15.html
2 of 4 08/31/2011 10:51 AM
startup le is executed in the same namespace as the interactive commands, and
removing the names avoids creating side eects in the interactive environment.
You may nd 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
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
... le:
A.1
Python will execute the contents of a le identied by the PYTHONSTARTUP
environment variable when you start an interactive interpreter.
A. Interactive Input Editing and History Substitution http://www.vithon.org/tutorial/2.5/node15.html
3 of 4 08/31/2011 10:51 AM
Release 2.5, documentation updated on 19th September, 2006.
See About this document... for information on suggesting changes.
A. Interactive Input Editing and History Substitution http://www.vithon.org/tutorial/2.5/node15.html
4 of 4 08/31/2011 10:51 AM
Python Tutorial
This Appendix was left untranslated.
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 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
B. Floating Point Arithmetic: Issues and Limitations http://www.vithon.org/tutorial/2.5/node16.html
1 of 5 08/31/2011 10:52 AM
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
repr(float) produces 17 signicant digits because it turns out that's enough
(on most machines) so that eval(repr(x)) == x exactly for all nite oats x,
but rounding to 16 digits is not enough to make that true.
Note that this is in the very nature of binary oating-point: this is not a bug
in Python, and it is not a bug in your code either. You'll see the same kind of
thing in all languages that support your hardware's oating-point arithmetic
(although some languages may not display the dierence by default, or in all
output modes).
Python's builtin str() function produces only 12 signicant 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
B. Floating Point Arithmetic: Issues and Limitations http://www.vithon.org/tutorial/2.5/node16.html
2 of 5 08/31/2011 10:52 AM
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.
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 oating-point representation is assumed.
Representation error refers to the fact that some (most, actually) decimal
fractions cannot be represented exactly as binary (base 2) fractions. This is
B. Floating Point Arithmetic: Issues and Limitations http://www.vithon.org/tutorial/2.5/node16.html
3 of 5 08/31/2011 10:52 AM
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
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!
B. Floating Point Arithmetic: Issues and Limitations http://www.vithon.org/tutorial/2.5/node16.html
4 of 5 08/31/2011 10:52 AM
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
meaning that the exact number stored in the computer is approximately
equal to the decimal value 0.100000000000000005551115123125. Rounding
that to 17 signicant 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!).
Release 2.5, documentation updated on 19th September, 2006.
See About this document... for information on suggesting changes.
B. Floating Point Arithmetic: Issues and Limitations http://www.vithon.org/tutorial/2.5/node16.html
5 of 5 08/31/2011 10:52 AM
Python Tutorial
This Appendix was left untranslated.
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-prot organization created
specically 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 Denition). Historically, most, but not all, Python releases have
also been GPL-compatible; the table below summarizes the various releases.
Release Derived from Year Owner GPL compatible?
0.9.0 thru 1.2 n/a 1991-1995 CWI yes
1.3 thru 1.5.2 1.2 1995-1999 CNRI yes
1.6 1.5.2 2000 CNRI no
2.0 1.6 2000 BeOpen.com no
1.6.1 1.6 2001 CNRI no
2.1 2.0+1.6.1 2001 PSF no
2.0.1 2.0+1.6.1 2001 PSF yes
2.1.1 2.1+2.0.1 2001 PSF yes
2.2 2.1.1 2001 PSF yes
2.1.2 2.1.1 2002 PSF yes
2.1.3 2.1.2 2002 PSF yes
2.2.1 2.2 2002 PSF yes
C. History and License http://www.vithon.org/tutorial/2.5/node17.html
1 of 13 08/31/2011 10:54 AM
Release Derived from Year Owner GPL compatible?
2.2.2 2.2.1 2002 PSF yes
2.2.3 2.2.2 2002-2003 PSF yes
2.3 2.2.2 2002-2003 PSF yes
2.3.1 2.3 2002-2003 PSF yes
2.3.2 2.3.1 2003 PSF yes
2.3.3 2.3.2 2003 PSF yes
2.3.4 2.3.3 2004 PSF yes
2.3.5 2.3.4 2005 PSF yes
2.4 2.3 2004 PSF yes
2.4.1 2.4 2005 PSF yes
2.4.2 2.4.1 2005 PSF yes
2.4.3 2.4.2 2006 PSF yes
2.5 2.4 2006 PSF 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.
C.2 Terms and conditions for accessing
or otherwise using Python
PSF LICENSE AGREEMENT FOR PYTHON 2.5
This LICENSE AGREEMENT is between the Python Software Foundation
(``PSF''), and the Individual or Organization (``Licensee'') accessing and
otherwise using Python 2.5 software in source or binary form and its
associated documentation.
1.
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.5 alone or in any
derivative version, provided, however, that PSF's License Agreement and
PSF's notice of copyright, i.e., ``Copyright 2001-2006 Python Software
Foundation; All Rights Reserved'' are retained in Python 2.5 alone or in
any derivative version prepared by Licensee.
2.
In the event Licensee prepares a derivative work that is based on or
incorporates Python 2.5 or any part thereof, and wants to make the
3.
C. History and License http://www.vithon.org/tutorial/2.5/node17.html
2 of 13 08/31/2011 10:54 AM
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.5.
PSF is making Python 2.5 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.5 WILL NOT INFRINGE ANY THIRD
PARTY RIGHTS.
4.
PSF SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF
PYTHON 2.5 FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL
DAMAGES OR LOSS AS A RESULT OF MODIFYING, DISTRIBUTING, OR
OTHERWISE USING PYTHON 2.5, OR ANY DERIVATIVE THEREOF,
EVEN IF ADVISED OF THE POSSIBILITY THEREOF.
5.
This License Agreement will automatically terminate upon a material
breach of its terms and conditions.
6.
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.
7.
By copying, installing or otherwise using Python 2.5, Licensee agrees to
be bound by the terms and conditions of this License Agreement.
8.
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 oce 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'').
1.
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.
2.
BeOpen is making the Software available to Licensee on an ``AS IS''
basis. BEOPEN MAKES NO REPRESENTATIONS OR WARRANTIES,
3.
C. History and License http://www.vithon.org/tutorial/2.5/node17.html
3 of 13 08/31/2011 10:54 AM
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.
4.
This License Agreement will automatically terminate upon a material
breach of its terms and conditions.
5.
This License Agreement shall be governed by and interpreted in all
respects by the law of the State of California, excluding conict 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.
6.
By copying, installing or otherwise using the software, Licensee agrees to
be bound by the terms and conditions of this License Agreement.
7.
CNRI LICENSE AGREEMENT FOR PYTHON 1.6.1
This LICENSE AGREEMENT is between the Corporation for National
Research Initiatives, having an oce 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.
1.
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
2.
C. History and License http://www.vithon.org/tutorial/2.5/node17.html
4 of 13 08/31/2011 10:54 AM
on the Internet using the following unique, persistent identier (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.
3.
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.
4.
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.
5.
This License Agreement will automatically terminate upon a material
breach of its terms and conditions.
6.
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 conict 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.
7.
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.
8.
ACCEPT
C. History and License http://www.vithon.org/tutorial/2.5/node17.html
5 of 13 08/31/2011 10:54 AM
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 specic, 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.
C.3 Licenses and Acknowledgements
for Incorporated Software
This section is an incomplete, but growing list of licenses and
acknowledgements for third-party software incorporated in the Python
distribution.
C.3.1 Mersenne Twister
The _random module includes code based on a download from
http://www.math.keio.ac.jp/~matumoto/MT2002/emt19937ar.html. The
following are the verbatim comments from the original code:
A C-program for MT19937, with initialization improved 2002/1/26.
Coded by Takuji Nishimura and Makoto Matsumoto.
Before using, initialize the state by using init_genrand(seed)
or init_by_array(init_key, key_length).
Copyright (C) 1997 - 2002, Makoto Matsumoto and Takuji Nishimura,
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
C. History and License http://www.vithon.org/tutorial/2.5/node17.html
6 of 13 08/31/2011 10:54 AM
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
C. History and License http://www.vithon.org/tutorial/2.5/node17.html
7 of 13 08/31/2011 10:54 AM
without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND
GAI_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 PROJECT OR CONTRIBUTORS BE LIABLE
FOR GAI_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 GAI_ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN GAI_ANY WAY
OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
SUCH DAMAGE.
C.3.3 Floating point exception control
The source for the fpectl module includes the following notice:
---------------------------------------------------------------------
/ Copyright (c) 1996. \
| The Regents of the University of California. |
| All rights reserved. |
| |
| Permission to use, copy, modify, and distribute this software for |
| any purpose without fee is hereby granted, provided that this en- |
| tire notice is included in all copies of any software which is or |
| includes a copy or modification of this software and in all |
| copies of the supporting documentation for such software. |
| |
| This work was produced at the University of California, Lawrence |
| Livermore National Laboratory under contract no. W-7405-ENG-48 |
| between the U.S. Department of Energy and The Regents of the |
| University of California for the operation of UC LLNL. |
| |
| DISCLAIMER |
| |
| This software was prepared as an account of work sponsored by an |
| agency of the United States Government. Neither the United States |
| Government nor the University of California nor any of their em- |
| ployees, makes any warranty, express or implied, or assumes any |
| liability or responsibility for the accuracy, completeness, or |
| usefulness of any information, apparatus, product, or process |
| disclosed, or represents that its use would not infringe |
| privately-owned rights. Reference herein to any specific commer- |
| cial products, process, or service by trade name, trademark, |
| manufacturer, or otherwise, does not necessarily constitute or |
| imply its endorsement, recommendation, or favoring by the United |
| States Government or the University of California. The views and |
| opinions of authors expressed herein do not necessarily state or |
| reflect those of the United States Government or the University |
C. History and License http://www.vithon.org/tutorial/2.5/node17.html
8 of 13 08/31/2011 10:54 AM
| of California, and shall not be used for advertising or product |
\ endorsement purposes. /
---------------------------------------------------------------------
C.3.4 MD5 message digest algorithm
The source code for the md5 module contains the following notice:
Copyright (C) 1999, 2002 Aladdin Enterprises. All rights reserved.
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
L. Peter Deutsch
ghost@aladdin.com
Independent implementation of MD5 (RFC 1321).
This code implements the MD5 Algorithm defined in RFC 1321, whose
text is available at
http://www.ietf.org/rfc/rfc1321.txt
The code is derived from the text of the RFC, including the test suite
(section A.5) but excluding the rest of Appendix A. It does not include
any code or documentation that is identified in the RFC as being
copyrighted.
The original and principal author of md5.h is L. Peter Deutsch
<ghost@aladdin.com>. Other authors are noted in the change history
that follows (in reverse chronological order):
2002-04-13 lpd Removed support for non-ANSI compilers; removed
references to Ghostscript; clarified derivation from RFC 1321;
now handles byte order either statically or dynamically.
1999-11-04 lpd Edited comments slightly for automatic TOC extraction.
1999-10-18 lpd Fixed typo in header comment (ansi2knr rather than md5);
added conditionalization for C++ compilation from Martin
Purschke <purschke@bnl.gov>.
C. History and License http://www.vithon.org/tutorial/2.5/node17.html
9 of 13 08/31/2011 10:54 AM
1999-05-03 lpd Original version.
C.3.5 Asynchronous socket services
The asynchat and asyncore modules contain the following notice:

Copyright 1996 by Sam Rushing
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 Sam
Rushing not be used in advertising or publicity pertaining to
distribution of the software without specific, written prior
permission.
SAM RUSHING DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN
NO EVENT SHALL SAM RUSHING 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.
C.3.6 Cookie management
The Cookie module contains the following notice:
Copyright 2000 by Timothy O'Malley <timo@alum.mit.edu>
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
Timothy O'Malley not be used in advertising or publicity
pertaining to distribution of the software without specific, written
prior permission.
Timothy O'Malley DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS
SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS, IN NO EVENT SHALL Timothy O'Malley BE LIABLE FOR
ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
C. History and License http://www.vithon.org/tutorial/2.5/node17.html
10 of 13 08/31/2011 10:54 AM
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.
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.
C.3.8 Execution tracing
The trace module contains the following notice:
portions copyright 2001, Autonomous Zones Industries, Inc., all rights...
err... reserved and offered to the public under the terms of the
Python 2.2 license.
Author: Zooko O'Whielacronx
http://zooko.com/
mailto:zooko@zooko.com
Copyright 2000, Mojam Media, Inc., all rights reserved.
Author: Skip Montanaro
Copyright 1999, Bioreason, Inc., all rights reserved.
Author: Andrew Dalke
Copyright 1995-1997, Automatrix, Inc., all rights reserved.
C. History and License http://www.vithon.org/tutorial/2.5/node17.html
11 of 13 08/31/2011 10:54 AM
Author: Skip Montanaro
Copyright 1991-1995, Stichting Mathematisch Centrum, all rights reserved.
Permission to use, copy, modify, and distribute this Python software and
its associated documentation for any purpose 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 neither Automatrix,
Bioreason or Mojam Media be used in advertising or publicity pertaining to
distribution of the software without specific, written prior permission.
C.3.9 UUencode and UUdecode functions
The uu module contains the following notice:
Copyright 1994 by Lance Ellinghouse
Cathedral City, California Republic, United States of America.
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 Lance Ellinghouse
not be used in advertising or publicity pertaining to distribution
of the software without specific, written prior permission.
LANCE ELLINGHOUSE DISCLAIMS ALL WARRANTIES WITH REGARD TO
THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
FITNESS, IN NO EVENT SHALL LANCE ELLINGHOUSE 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.
Modified by Jack Jansen, CWI, July 1995:
- Use binascii module to do the actual line-by-line conversion
between ascii and binary. This results in a 1000-fold speedup. The C
version is still 5 times faster, though.
- Arguments more compliant with python standard
C.3.10 XML Remote Procedure Calls
The xmlrpclib module contains the following notice:
The XML-RPC client interface is
Copyright (c) 1999-2002 by Secret Labs AB
Copyright (c) 1999-2002 by Fredrik Lundh
C. History and License http://www.vithon.org/tutorial/2.5/node17.html
12 of 13 08/31/2011 10:54 AM
By obtaining, using, and/or copying this software and/or its
associated documentation, you agree that you have read, understood,
and will comply with the following terms and conditions:
Permission to use, copy, modify, and distribute this software and
its associated documentation for any purpose and 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
Secret Labs AB or the author not be used in advertising or publicity
pertaining to distribution of the software without specific, written
prior permission.
SECRET LABS AB AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD
TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANT-
ABILITY AND FITNESS. IN NO EVENT SHALL SECRET LABS AB OR THE AUTHOR
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.
Release 2.5, documentation updated on 19th September, 2006.
See About this document... for information on suggesting changes.
C. History and License http://www.vithon.org/tutorial/2.5/node17.html
13 of 13 08/31/2011 10:54 AM
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.
D. Glossary http://www.vithon.org/tutorial/2.5/node18.html
1 of 6 08/31/2011 10:59 AM
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
the expression 11/4 would evaluate to 2.75. By importing the __future__
module and evaluating its variables, you can see when a new feature was rst
added to the language and when it will become the default:
>>> import __future__
>>> __future__.division
_Feature((2, 2, 0, 'alpha', 2), (3, 0, 0, 'alpha', 0), 8192)
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
D. Glossary http://www.vithon.org/tutorial/2.5/node18.html
2 of 6 08/31/2011 10:59 AM
element is requested by calling the next() method of the returned iterator.
generator expression
An expression that returns a generator. It looks like a normal expression
followed by a for expression dening a loop variable, range, and an optional if
expression. The combined expression generates values for an enclosing
function:
>>> sum(i*i for i in range(10)) # sum of squares 0, 1, 4, ... 81
285
GIL
See global interpreter lock.
global interpreter lock
The lock used by Python threads to assure that only one thread can be run at a
time. This simplies Python by assuring that no two processes can access the
same memory at the same time. Locking the entire interpreter makes it easier
for the interpreter to be multi-threaded, at the expense of some parallelism on
multi-processor machines. Eorts have been made in the past to create a
``free-threaded'' interpreter (one which locks shared data at a much ner
granularity), but performance suered in the common single-processor case.
IDLE
An Integrated Development Environment for Python. IDLE is a basic editor and
interpreter environment that ships with the standard distribution of Python.
Good for beginners, it also serves as clear example code for those wanting to
implement a moderately sophisticated, multi-platform GUI application.
immutable
An object with xed value. Immutable objects are numbers, strings or tuples
(and more). Such an object cannot be altered. A new object has to be created if
a dierent value has to be stored. They play an important role in places where
a constant hash value is needed, for example as a key in a dictionary.
integer division
Mathematical division discarding any remainder. For example, the expression
11/4 currently evaluates to 2 in contrast to the 2.75 returned by oat division.
Also called oor division. When dividing two integers the outcome will always
be another integer (having the oor function applied to it). However, if one of
the operands is another numeric type (such as a float), the result will be
coerced (see coercion) to a common type. For example, an integer divided by a
oat will result in a oat value, possibly with a decimal fraction. Integer
division can be forced by using the // operator instead of the / operator. See
also __future__.
interactive
Python has an interactive interpreter which means that you can try out things
and immediately see their results. Just launch python with no arguments
(possibly by selecting it from your computer's main menu). It is a very powerful
way to test out new ideas or inspect modules and packages (remember
help(x)).
D. Glossary http://www.vithon.org/tutorial/2.5/node18.html
3 of 6 08/31/2011 10:59 AM
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,
D. Glossary http://www.vithon.org/tutorial/2.5/node18.html
4 of 6 08/31/2011 10:59 AM
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
D. Glossary http://www.vithon.org/tutorial/2.5/node18.html
5 of 6 08/31/2011 10:59 AM
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.
D. Glossary http://www.vithon.org/tutorial/2.5/node18.html
6 of 6 08/31/2011 10:59 AM

You might also like