Professional Documents
Culture Documents
Python
Python
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 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.
Contents
1. Khai v ..................................................................................................................... 6
2. S dng trnh thng dch Python ............................................................................. 8
2.1 Chy trnh thng dch ......................................................................................... 8
2.1.1 Truyn thng s ........................................................................................... 9
2.1.2 Ch tng tc .......................................................................................... 9
2.2 Trnh thng dch v mi trng ca n ........................................................... 10
2.2.1 X l li ..................................................................................................... 10
2.2.2 Cc kch bn Python kh thi ...................................................................... 10
2.2.3 Bng m m ngun .................................................................................... 11
2.2.4 Tp tin khi to tng tc .......................................................................... 12
3. Gii thiu s v Python ......................................................................................... 13
3.1 Dng Python nh l my tnh .......................................................................... 13
3.1.1 S ............................................................................................................... 13
3.1.2 Chui .......................................................................................................... 17
3.1.3 Chui Unicode ........................................................................................... 23
3.1.4 Danh sch ................................................................................................... 25
3.2 Nhng bc u lp trnh ................................................................................ 28
4. Bn thm v lung iu khin ............................................................................... 31
4.1 if cu lnh ......................................................................................................... 31
4.2 for cu lnh ....................................................................................................... 31
4.3 range() hm ...................................................................................................... 32
4.4 break v continue cu lnh, v else v lp ....................................................... 33
4.5 pass cu lnh .................................................................................................... 34
4.6 nh ngha hm ................................................................................................ 34
4.7 Bn thm v nh ngha hm............................................................................ 37
4.7.1 Gi tr thng s mc nh........................................................................... 37
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 file) 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.
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.
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 file. 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-offile) 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 file) 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.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:
python
Python 1.5.2b2 (#1, Feb 28 1999, 00:02:06)
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:
...
...
Be careful not to fall off!
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.1G 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 .
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") 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
currency = u""
print ord(currency)
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
4
>>> (50-5*6)/4
5
>>> # Integer division returns the floor:
... 7/3
2
>>> 7/-3
-3
# Zero x, y and z
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
# 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
>>>
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"
"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
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
-H hostname
Hostname to connect to
xut ra:
Usage: thingy [OPTIONS]
-h
-H hostname
Hostname to connect to
<-
This is ok
'string'
>>> 'str'.strip() + 'ing'
<-
This is ok
<-
This is invalid
'string'
>>> 'str'.strip() 'ing'
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.
>>> word[:2]
'He'
>>> word[2:]
'lpA'
Cc ch mc c th l s m, bt u m t bn phi. V d:
>>> word[-1]
'A'
>>> word[-2]
'p'
>>> word[-2:]
'pA'
>>> word[:-2]
'Hel'
# (since -0 equals 0)
'H'
# error
-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.
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.
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.
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 range(128)
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]
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')
>>> p
[1, [2, 3, 'xtra'], 4]
>>> q
[2, 3, 'xtra']
print b
...
a, b = b, a+b
...
1
1
2
3
5
8
>>> 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
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
...
... 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.
print x, len(x)
...
cat 3
window 6
defenestrate 12
...
>>> 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]
[5, 6, 7, 8, 9]
>>> range(0, 10, 3)
[0, 3, 6, 9]
>>> range(-10, -100, -30)
[-10, -40, -70]
print i, a[i]
...
0 Mary
1 had
2 a
3 little
4 lamb
, nh trong C, nhy ra khi phm vng lp for hay while nh nht cha n.
continue
...
if n % x == 0:
...
...
break
...
else:
...
...
...
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.6 nh ngha hm
Chng ta c th to mt hm in ra dy Fibonacci:
>>> def fib(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
...
result = []
...
a, b = 0, 1
...
while b < n:
...
result.append(b)
...
a, b = b, a+b
...
# see below
return result
...
>>> f100 = fib2(100)
# call it
>>> f100
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
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)
S in ra
[1]
[1, 2]
[1, 2, 3]
parrot(voltage=5.0, 'dead')
keyword
parrot(110, voltage=220)
parrot(actor='John Cleese')
# unknown keyword
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()
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.
[3, 4, 5]
>>> args = [3, 6]
>>> range(*args)
list
[3, 4, 5]
...
...
...
>>> 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 !
a+b".
return lambda x: x + n
...
>>> f = make_incrementor(42)
>>> f(0)
42
>>> f(1)
43
u l v d ca mt docstring a dng:
>>> def my_function():
...
...
...
...
"""
...
pass
...
>>> print my_function.__doc__
Do nothing, but document it.
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.
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)
count(x)
# Terry arrives
>>> queue.append("Graham")
# Graham arrives
>>> queue.pop(0)
'Eric'
>>> queue.pop(0)
'John'
>>> queue
['Michael', 'Terry', 'Graham']
...
...
>>> sum(range(1, 11))
55
>>> sum([])
0
banana', '
']
^
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]
>>> del a
5.3 B v dy
Chng ta thy rng danh sch v chui c nhiu thuc tnh chung, nh l c ch mc, v
cc ton t ct ming. Chng l hai v d ca dy (sequence) kiu d liu. V Python l mt
ngn ng ang pht trin, cc kiu d liu dy khc c th c thm vo. C mt kiu dy
chun khc: b (tuple).
Mt tuple gm mt s cc gi tr phn cch bi du phy, v d:
>>> t = 12345, 54321, 'hello!'
>>> t[0]
12345
>>> t
(12345, 54321, 'hello!')
>>> # Tuples may be nested:
... u = t, (1, 2, 3, 4, 5)
>>> u
((12345, 54321, 'hello!'), (1, 2, 3, 4, 5))
Khi xut ra, tuple lun lun c km gia hai du ngoc nhm cho cc tuple lng nhau
c th c thng dch chnh xc; chng c th c nhp vo vi ngoc hoc khng, mc
d thng thng chng ta vn cn cc du ngoc (nu tuple l mt phn ca mt biu thc
ln hn).
Tuple c dng nhiu. V d: cp ta (x, y), bn ghi nhn vin t c s d liu, v.v...
Ging nh chui, tuple khng th b thay i: khng th gn gi tr mi cho tng phn t
ca tuple (mc d bn c th t c cng kt qu vi ct ming v ghp dy). Cng c
th to tuple cha cc i tng kh bin v d nh danh sch.
Vn c bit l trong vic to nn tuple cha 0 hoc mt phn t: c php ngn ng c
mt vi im ring thc hin vic ny. Tuple rng c to nn bi mt cp ngoc rng;
tuple mt phn t c to bi mt gi tr theo sau bi mt du phy (vic cho gi tr n
l vo trong ngoc khng to tuple). Xu, nhng hiu qu. V d:
>>> empty = ()
>>> singleton = 'hello',
>>> len(empty)
0
>>> len(singleton)
1
>>> singleton
('hello',)
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)
duplicates
>>> fruit
set(['orange', 'pear', 'apple', 'banana'])
>>> 'orange' in fruit
True
>>> 'crabgrass' in fruit
False
# unique letters in a
# letters in either a or b
set(['a', 'c'])
>>> a ^ b
both
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 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
# use a list
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
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']
It is %s.' % (q, a)
...
What is your name?
What is your quest?
It is lancelot.
It is the holy grail.
It is blue.
print i
...
9
7
5
3
1
print f
pear
< (1, 2, 4)
[1, 2, 3]
< [1, 2, 4]
< (1, 2, 4)
(1, 2)
(1, 2, 3)
(1, 2, ('aa', 'ab'))
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 mun 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 fibo.py trong th mc hin ti vi ni dung sau:
# Fibonacci numbers module
def fib(n):
a, b = 0, 1
while b < n:
print b,
a, b = b, a+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 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'
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
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.
Hai bin ny ch c nh ngha khi trnh thng dch chy ch tng tc.
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']
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, .aiff, .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
Formats/
conversions
__init__.py
wavread.py
wavwrite.py
aiffread.py
aiffwrite.py
auread.py
auwrite.py
...
Effects/
__init__.py
echo.py
surround.py
reverse.py
...
Filters/
__init__.py
equalizer.py
vocoder.py
karaoke.py
...
Mt bin th khc l nhp hm hoc bin mnh mun mt cch trc tip:
from Sound.Effects.echo import echofilter
Lu rng khi s dng from package import item, item c th hoc l m-un con (hoc
gi con) ca gi, hoc l mt tn no khc c nh ngha trong 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/Effects/__init__.py c th cha
on m sau:
__all__ = ["echo", "surround", "reverse"]
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.
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.
str()
Mt vi v d:
>>> s = 'Hello, world.'
>>> str(s)
'Hello, world.'
>>> repr(s)
"'Hello, world.'"
>>> str(0.1)
'0.1'
>>> repr(0.1)
'0.10000000000000001'
>>> x = 10 * 3.25
>>> y = 200 * 200
>>> s = 'The value of x is ' + repr(x) + ', and y is ' + repr(y) +
'...'
>>> print s
The value of x is 32.5, and y is 40000...
>>> # The repr() of a string adds string quotes and backslashes:
... hello = 'hello, world\n'
>>> hellos = repr(hello)
>>> print hellos
'hello, world\n'
>>> # The argument to repr() may be any Python object:
... repr((x, y, ('spam', 'eggs')))
"(32.5, 40000, ('spam', 'eggs'))"
>>> # reverse quotes are convenient in interactive sessions:
... `x, y, ('spam', 'eggs')`
"(32.5, 40000, ('spam', 'eggs'))"
...
...
print repr(x*x*x).rjust(4)
...
1
27
16
64
25
125
36
216
49
343
64
512
81
729
10 100 1000
>>> for x in range(1,11):
...
...
1
27
16
64
25
125
36
216
49
343
64
512
81
729
10 100 1000
Jack
==>
4098
Dcab
==>
7678
Sjoerd
==>
4127
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.
>>> f.readline()
'This is the first line of the file.\n'
>>> f.readline()
'Second line of the file\n'
>>> f.readline()
''
>>> 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,
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)
>>> f.read(1)
'5'
>>> f.seek(-3, 2) # Go to the 3rd byte before the end
>>> f.read(1)
'd'
(C nhng bin th khc, dng khi gim nhiu i tng hoc khi bn khng mun vit d
liu gim vo tp tin; tham kho ton b ti liu v pickle trong Tham kho th vin
Python.)
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; 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.
pickle
8. Li v bit l
n by gi chng ta cng ch mi nhc n cc thng ip li, nhng nu bn th qua
cc v d th bn c th gp nhiu hn. C (t nht) hai loi li khc bit: li c php v
bit l.
8.1 Li c php
Li c php, cn bit n nh li phn tch (parsing error), c l l phn nn ln nht bn
gp phi khi vn ang hc Python:
>>> while True print 'Hello world'
File "<stdin>", line 1, in ?
while True print 'Hello world'
^
SyntaxError: invalid syntax
8.2 Bit l
Cho d mt cu lnh hoc biu thc l ng n, n vn c th to li khi thc thi. Nhng
li b pht hin trong lc thc thi c gi l bit l v khng tai hi mt cch v iu kin:
bn s hc cch x l chng trong cc chng trnh Python. Hu ht cc bit l u c
x l bi chng trnh v dn n kt qu l cc thng ip li nh y:
>>> 10 * (1/0)
Traceback (most recent call last):
File "<stdin>", line 1, in ?
ZeroDivisionError: integer division or modulo by zero
>>> 4 + spam*3
Traceback (most recent call last):
File "<stdin>", line 1, in ?
NameError: name 'spam' is not defined
>>> '2' + 2
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, 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
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.
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
...
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!'
>>> try:
...
raise KeyboardInterrupt
... finally:
...
print 'Goodbye, world!'
...
Goodbye, world!
Traceback (most recent call last):
File "<stdin>", line 2, in ?
KeyboardInterrupt
A v finally 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)
division by zero!
executing finally clause
>>> divide("2", "1")
executing finally clause
Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "<stdin>", line 3, in divide
TypeError: unsupported operand type(s) for /: 'str' and 'str'
8.7 nh ngha x l c sn
Mt s i tng nh ngha cc tc v dn dp chun thc thi khi mt i tng khng
cn c cn n, cho d vic x dng i tng l thnh cng hay tht bi. Xem qua v d
sau, n th m mt tp tin v vit ni dung ca n ra mn hnh.
for line in open("myfile.txt"):
print line
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.
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.
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.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'
...
self.i = imagpart
...
>>> x = Complex(3.0, -4.5)
>>> x.r, x.i
(3.0, -4.5)
Loi tham chiu thuc tnh trng hp khc l mt method (phng thc). Mt phng
thc l mt hm ``ca'' mt i tng. (Trong Python, t phng thc khng ch ring cho
trng hp lp: cc kiu i tng khc cng c th c phng thc. V d, i tng danh
sch c phng thc tn append, insert, remove, sort, v.v... Tuy nhin, trong phn sau
chng ta s ch dng t phng thc d ch cc phng thc ca i tng trng hp lp,
tr khi c ch nh khc i.)
Cc tn phng thc hp l ca mt i tng trng hp ph thuc vo lp ca n. Theo
nh ngha, mi thuc tnh ca mt lp m l nhng i tng hm nh ngha cc phng
thc tng ng ca cc trng hp ca lp . Trong v d ca chng ta, x.f l mt tham
chiu phng thc hp l, v MyClass.f l mt hm, nhng x.i khng phi, bi v
MyClass.i khng phi. Nhng x.f khng phi l mt th nh MyClass.f -- n l mt
method object (i tng phng thc), khng phi l mt i tng hm.
Trong MyClass , n s tr v chui 'hello world'. Tuy nhin, cng khng nht thit phi
gi mt phng thc ngay lp tc: x.f l mt i tng phng thc, v c th c ct i
v gi vo mt thi im khc. V d:
xf = x.f
while True:
print xf()
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.
class C:
f = f1
def g(self):
return 'hello world'
h = g
9.5 K tha
D nhin, mt tnh nng ngn ng s khng ng c gi l ``lp'' nu n khng h tr k
tha. C php ca mt nh ngha lp con nh sau:
class DerivedClassName(BaseClassName):
<statement-1>
.
.
.
<statement-N>
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.
raise instance
except C:
print "C"
except B:
print "B"
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 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()
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]
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 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]
print char
...
f
l
o
g
# sum of squares
# dot product
260
for word in
(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>
Cch thot khi mt kch bn mt cch trc tip nht l dng "sys.exit()".
>>> 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'
10.6 Ton hc
math
10.8 Ngy v gi
(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.
datetime
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
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
def average(values):
"""Computes the arithmetic mean of a list of numbers.
>>> print average([20, 30, 70])
40.0
"""
return sum(values, 0.0) / len(values)
import doctest
doctest.testmod()
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, [])
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:
11.1 nh dng ra
(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:
repr
11.2 To mu
(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.
string
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.
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
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
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
(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:
logging
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')
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.
>>> 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 -topleveld['primary']
# entry was automatically
removed
File "C:/PY24/lib/weakref.py", line 46, in __getitem__
o = self.data[key]()
KeyError: 'primary'
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')]
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')
Decimal("0.7350")
>>> .70 * 1.05
0.73499999999999999
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
>>> getcontext().prec = 36
>>> Decimal(1) / Decimal(7)
Decimal("0.142857142857142857142857142857142857")
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.
prompt to mark a line as modified. Pressing the Return key passes the current line to the
interpreter. C-R starts an incremental reverse search; C-S starts a forward search.
or
"string": function-name
For example:
# I prefer vi-style editing:
set editing-mode vi
Note that the default binding for Tab in Python is to insert a Tab character instead of
Readline's default filename completion function. If you insist, you can override this by
putting
Tab: complete
in your ~/.inputrc. (Of course, this makes it harder to type indented continuation lines 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 file: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 final "." and then suggest completions from the attributes of the
resulting object. Note that this may execute application-defined code if an object with a
__getattr__() method is part of the expression.
A more capable startup file might look like this example. Note that this deletes the names it
creates once they are no longer needed; this is done since the startup file is executed in the
same namespace as the interactive commands, and removing the names avoids creating side
effects in the interactive environment. You may find it convenient to keep some of the
imported modules, such as os, which turn out to be needed in most sessions with the
interpreter.
# Add auto-completion and a stored history file of commands to
your Python
# interactive interpreter. Requires Python 2.0+, readline.
Autocomplete is
# bound to the Esc key by default (you can change it - see
readline docs).
#
# Store the file in ~/.pystartup, and set an environment variable
to point
# to it:
bash.
#
"export PYTHONSTARTUP=/max/home/itamar/.pystartup" in
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.
has value 1/10 + 2/100 + 5/1000, and in the same way the binary fraction
0.001
has value 0/2 + 0/4 + 1/8. These two fractions have identical values, the only real difference
being that the first is written in base 10 fractional notation, and the second in base 2.
Unfortunately, most decimal fractions cannot be represented exactly as binary fractions. A
consequence is that, in general, the decimal floating-point numbers you enter are only
approximated by the binary floating-point numbers actually stored in the machine.
The problem is easier to understand at first in base 10. Consider the fraction 1/3. You can
approximate that as a base 10 fraction:
0.3
or, better,
0.33
or, better,
0.333
and so on. No matter how many digits you're willing to write down, the result will never be
exactly 1/3, but will be an increasingly better approximation 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 infinitely
repeating fraction
0.0001100110011001100110011001100110011001100110011...
Stop at any finite number of bits, and you get an approximation. This is why you see things
like:
>>> 0.1
0.10000000000000001
On most machines today, that is what you'll see if you enter 0.1 at a Python prompt. You
may not, though, because the number of bits used by the hardware to store floating-point
values can vary across machines, and Python only prints a decimal approximation to the
true decimal value of the binary approximation stored by the machine. On most machines,
if Python were to print the true decimal value of the binary approximation stored for 0.1, it
would have to display
>>> 0.1
0.1000000000000000055511151231257827021181583404541015625
instead! The Python prompt uses the builtin repr() function to obtain a string version of
everything it displays. For floats, repr(float) rounds the true decimal value to 17
significant digits, giving
0.10000000000000001
repr(float)
produces 17 significant digits because it turns out that's enough (on most
machines) so that eval(repr(x)) == x exactly for all finite floats x, but rounding to 16
digits is not enough to make that true.
Note that this is in the very nature of binary floating-point: this is not a bug in Python, 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 floating-point arithmetic (although some languages may not
display the difference by default, or in all output modes).
Python's builtin str() function produces only 12 significant digits, and you may wish to
use that instead. It's unusual for eval(str(x)) to reproduce x, but the output may be more
pleasant to look at:
>>> print str(0.1)
0.1
It's important to realize that this is, in a real sense, an illusion: the value in the machine is
not exactly 1/10, you're simply rounding the display of the true machine value.
Other surprises follow from this one. For example, after seeing
>>> 0.1
0.10000000000000001
you may be tempted to use the round() function to chop it back to the single digit you
expect. But that makes no difference:
>>> round(0.1, 1)
0.10000000000000001
The problem is that the binary floating-point value stored for "0.1" was already the best
possible binary approximation to 1/10, so trying to round it again can't make it better: it was
already as good as it gets.
Another consequence is that since 0.1 is not exactly 1/10, 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 floating-point arithmetic holds many surprises like this. The problem with "0.1" is
explained in precise detail below, in the "Representation Error" section. See The Perils of
Floating Point for a more complete account of other common surprises.
As that says near the end, ``there are no easy answers.'' Still, don't be unduly wary of
floating-point! The errors in Python float operations are inherited from the floating-point
hardware, and on most machines are on the order of no more than 1 part in 2**53 per
operation. That's more than adequate for most tasks, but you do need to keep in mind that
it's not decimal arithmetic, and that every float operation can suffer a new rounding error.
While pathological cases do exist, for most casual use of floating-point arithmetic you'll see
the result you expect in the end if you simply round the display of your final results to the
number of decimal digits you expect. str() usually suffices, and for finer control see the
discussion of Python's % format operator: the %g, %f and %e format codes supply flexible
and easy ways to round float results for display.
Why is that? 1/10 is not exactly representable as a binary fraction. Almost all machines
today (November 2000) use IEEE-754 floating point arithmetic, and almost all platforms
map Python floats to IEEE-754 "double precision". 754 doubles contain 53 bits of precision,
so on input the computer strives to convert 0.1 to the closest fraction it can of the form
J/2**N where J is an integer containing exactly 53 bits. Rewriting
1 / 10 ~= J / (2**N)
as
J ~= 2**N / 10
and recalling that J has exactly 53 bits (is >= 2**52 but < 2**53), the best value for N is
56:
>>> 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!
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
significant 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 significant digits gives
the 0.10000000000000001 that Python displays (well, will display on any 754-conforming
platform that does best-possible input and output conversions in its C library -- yours may
not!).
Owner
GPL compatible?
1991-1995 CWI
yes
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
Release
Owner
GPL compatible?
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
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 modified version without making your changes open
source. The GPL-compatible licenses make it possible to combine Python with other software that
is released under the GPL; the others don't.
Thanks to the many outside volunteers who have worked under Guido's direction to make these
releases possible.
C.2 Terms and conditions for accessing or otherwise using Python
This LICENSE AGREEMENT is between BeOpen.com (``BeOpen''), having an office at 160 Saratoga
Avenue, Santa Clara, CA 95051, and the Individual or Organization (``Licensee'') accessing and
otherwise using this software in source or binary form and its associated documentation (``the
Software'').
Subject to the terms and conditions of this BeOpen Python License Agreement, BeOpen hereby
grants Licensee a non-exclusive, royalty-free, world-wide license to reproduce, analyze, test,
perform and/or display publicly, prepare derivative works, distribute, and otherwise use the
Software alone or in any derivative version, provided, however, that the BeOpen Python License is
retained in the Software, alone or in any derivative version prepared by Licensee.
BeOpen is making the Software available to Licensee on an ``AS IS'' basis. BEOPEN MAKES NO
REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED. BY WAY OF EXAMPLE, BUT NOT
LIMITATION, BEOPEN MAKES NO AND DISCLAIMS ANY REPRESENTATION OR WARRANTY OF
MERCHANTABILITY OR FITNESS FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF THE
SOFTWARE WILL NOT INFRINGE ANY THIRD PARTY RIGHTS.
BEOPEN SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF THE SOFTWARE FOR ANY
INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS A RESULT OF USING,
MODIFYING OR DISTRIBUTING THE SOFTWARE, OR ANY DERIVATIVE THEREOF, EVEN IF ADVISED
OF THE POSSIBILITY THEREOF.
This License Agreement will automatically terminate upon a material breach of its terms and
conditions.
This License Agreement shall be governed by and interpreted in all respects by the law of the State
of California, excluding conflict of law provisions. Nothing in this License Agreement shall be
deemed to create any relationship of agency, partnership, or joint venture between BeOpen and
Licensee. This License Agreement does not grant permission to use BeOpen trademarks or trade
names in a trademark sense to endorse or promote products or services of Licensee, or any third
party. As an exception, the ``BeOpen Python'' logos available at
http://www.pythonlabs.com/logos.html may be used according to the permissions granted on
that web page.
By copying, installing or otherwise using the software, Licensee agrees to be bound by the terms
and conditions of this License Agreement.
CNRI LICENSE AGREEMENT FOR PYTHON 1.6.1
This LICENSE AGREEMENT is between the Corporation for National Research Initiatives, having an
office at 1895 Preston White Drive, Reston, VA 20191 (``CNRI''), and the Individual or Organization
(``Licensee'') accessing and otherwise using Python 1.6.1 software in source or binary form and its
associated documentation.
Subject to the terms and conditions of this License Agreement, CNRI hereby grants Licensee a
nonexclusive, royalty-free, world-wide license to reproduce, analyze, test, perform and/or display
publicly, prepare derivative works, distribute, and otherwise use Python 1.6.1 alone or in any
derivative version, provided, however, that CNRI's License Agreement and CNRI's notice of
copyright, i.e., ``Copyright 1995-2001 Corporation for National Research Initiatives; All Rights
Reserved'' are retained in Python 1.6.1 alone or in any derivative version prepared by Licensee.
Alternately, in lieu of CNRI's License Agreement, Licensee may substitute the following text
(omitting the quotes): ``Python 1.6.1 is made available subject to the terms and conditions in
CNRI's License Agreement. This Agreement together with Python 1.6.1 may be located on the
Internet using the following unique, persistent identifier (known as a handle): 1895.22/1013. This
Agreement may also be obtained from a proxy server on the Internet using the following URL:
http://hdl.handle.net/1895.22/1013.''
In the event Licensee prepares a derivative work that is based on or incorporates Python 1.6.1 or
any part thereof, and wants to make the derivative work available to others as provided herein,
then Licensee hereby agrees to include in any such work a brief summary of the changes made to
Python 1.6.1.
CNRI is making Python 1.6.1 available to Licensee on an ``AS IS'' basis. CNRI MAKES NO
REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED. BY WAY OF EXAMPLE, BUT NOT
LIMITATION, CNRI MAKES NO AND DISCLAIMS ANY REPRESENTATION OR WARRANTY OF
MERCHANTABILITY OR FITNESS FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF PYTHON
1.6.1 WILL NOT INFRINGE ANY THIRD PARTY RIGHTS.
CNRI SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF PYTHON 1.6.1 FOR ANY
INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS A RESULT OF MODIFYING,
DISTRIBUTING, OR OTHERWISE USING PYTHON 1.6.1, OR ANY DERIVATIVE THEREOF, EVEN IF
ADVISED OF THE POSSIBILITY THEREOF.
This License Agreement will automatically terminate upon a material breach of its terms and
conditions.
This License Agreement shall be governed by the federal intellectual property law of the United
States, including without limitation the federal copyright law, and, to the extent such U.S. federal
law does not apply, by the law of the Commonwealth of Virginia, excluding Virginia's conflict of
law provisions. Notwithstanding the foregoing, with regard to derivative works based on Python
1.6.1 that incorporate non-separable material that was previously distributed under the GNU
General Public License (GPL), the law of the Commonwealth of Virginia shall govern this License
Agreement only as to issues arising under or with respect to Paragraphs 4, 5, and 7 of this License
Agreement. Nothing in this License Agreement shall be deemed to create any relationship of
agency, partnership, or joint venture between CNRI and Licensee. This License Agreement does
not grant permission to use CNRI trademarks or trade name in a trademark sense to endorse or
promote products or services of Licensee, or any third party.
By clicking on the ``ACCEPT'' button where indicated, or by copying, installing or otherwise using
Python 1.6.1, Licensee agrees to be bound by the terms and conditions of this License Agreement.
ACCEPT
CWI LICENSE AGREEMENT FOR PYTHON 0.9.0 THROUGH 1.2
Copyright 1991 - 1995, Stichting Mathematisch Centrum Amsterdam, The Netherlands. All
rights reserved.
Permission to use, copy, modify, and distribute this software and its documentation for any
purpose and without fee is hereby granted, provided that the above copyright notice appear in all
copies and that both that copyright notice and this permission notice appear in supporting
documentation, and that the name of Stichting Mathematisch Centrum or CWI not be used in
advertising or publicity pertaining to distribution of the software without specific, written prior
permission.
STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS
SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO
EVENT SHALL STICHTING MATHEMATISCH CENTRUM BE LIABLE FOR ANY SPECIAL, INDIRECT OR
CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE,
DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS
ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS
SOFTWARE.
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.
\
|
|
|
|
|
|
|
Permission to use, copy, modify, and distribute this
software for
|
|
any purpose without fee is hereby granted, provided that
this en|
|
is or
|
includes
in all
|
copy
or
modification
of
|
|
|
|
This work was produced at the University of California,
Lawrence
|
|
Livermore National Laboratory under
ENG-48
|
|
between
of the
|
|
the
U.S.
Department
of
contract
no.
W-7405-
|
|
|
|
DISCLAIMER
|
|
|
|
by an
This
|
|
agency of the United States Government. Neither the United
States
|
|
Government
their em|
|
ployees, makes any warranty, express or implied, or
assumes any
|
|
liability
completeness, or
or
|
responsibility
|
usefulness of any information,
process
|
|
disclosed,
infringe
|
or
represents
that
its
use
product,
would
or
not
|
privately-owned rights. Reference herein to any specific
commer|
|
cial
trademark,
products,
|
process,
or
service
|
manufacturer, or otherwise, does not
constitute or
|
|
imply
United
|
|
views
by trade name,
necessarily
|
opinions
state or
|
|
reflect those of the United States Government or
University
|
|
of California,
product
|
\
the
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.
reserved.
All rights
L. Peter Deutsch
ghost@aladdin.com
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.
include
It does not
This permission is
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 files so that executing the same file 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 floating
point number to the integer 3, but in 3+4.5, each argument is of a different type (one int,
one float), 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 suffix, 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.
descriptor
Any new-style object that defines 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 defined 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
specific types, well-designed code improves its flexibility 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 first 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 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 defining 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))
4, ... 81
285
GIL
See global interpreter lock.
global interpreter lock
# sum of squares 0, 1,
The lock used by Python threads to assure that only one thread can be run at a time. This
simplifies 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 multithreaded, at the expense of some parallelism on multi-processor machines. Efforts have
been made in the past to create a ``free-threaded'' interpreter (one which locks shared data
at a much finer granularity), but performance suffered 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 fixed 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 different 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 float division. Also called floor
division. When dividing two integers the outcome will always be another integer (having
the floor 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 float will result in a float 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)).
interpreted
Python is an interpreted language, as opposed to a compiled one. This means that the
source files can be run directly without first 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 define 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 definitions create a class name, a class dictionary, 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 conflicts. 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 definition. For instance, a function defined
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 efficient 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 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.
Ch mc
K hiu | _ | a | b | c | d | e | f | g | h | i | l | m | n | o | p | r | s | u | z
K hiu
...
>>>
_ (gch chn)
__all__
__future__
__slots__
A
append() (phng thc danh sch)
B
BDFL
C
classic class (lp c in)
coercion (p kiu)
descriptor
dictionary (t in)
E
EAFP
F
file object (i tng tp tin)
G
generator (b sinh, b to)
GIL
H
help() (hm c sn)
IDLE
iterator (b lp)
L
LBYL
M
mapping (nh x)
module (m-un)
N
namespace (vng tn)
O
object (i tng)
file (tp tin)
method (phng thc)
P
path (ng dn)
Python3000
R
readline (m-un c sn)
S
search (tm kim)
sequence (dy)
U
unicode() (hm c sn)
Zen of Python