Python Note

Page 1

Python ÆS)P X’ LeafWang@163bj.com or AnnCharles@tom.com

2003c08 26F


annCharles@tom.com

12 , 208

Python ÆS)P


8ยน

8ยน 1ย ร Python0 0

1

ยง1.1 mยฉ . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

2

ยง1.1.1 Xร $1PythonยงS . . . . . . . . . . . . . . . . . . . . . . . . . . . .

2

ยง1.2 ย ย ย รฉย . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

3

ยง1.3 ร a. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

3

ยง1.3.1 .(integer) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

3

ยง1.3.2 2:.(float) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

3

ยง1.3.3 Nonea. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

3

ยง1.3.4 ร 6Lย ยช . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

3

ยง1.4 L(list) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

6

ยง1.4.1 Mรฏlist . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

6

ยง1.4.2 list eIร flist . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

6

ยง1.4.3 flist J . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

7

ยง1.4.4 ?nlist ย { . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

8

ยง1.4.5 ^list [ร ยฆ~^รชรข( . . . . . . . . . . . . . . . . . . . . . . .

10

ยง1.4.6 list comprehension . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

12

ยง1.5 iร G(string) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

13

ยง1.5.1 iร G Lยซ . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

13

ยง1.5.2 =ย ยคย ร ยฆa. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

14

ยง1.5.3 iร G รถย . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

14

ยง1.6 |(tuple) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

22

ยง1.7 S (sequence) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

23

ยง1.8 i;(dictionary) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

23

ยง1.8.1 {รผ~f . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

24

ยง1.8.2 dictionary รถย . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

24

ยง1.9 ยงS6ยง . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

27

ยง1.9.1 ยฉ|( if . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

27

ยง1.9.2 ร ย ( forยงwhileยงbreakยงcontinueยงrange() . . . . . . . . . . . . .

29

annCharles@tom.com

1iย , 208ย

Python ร S)P


8š §1.10 Ÿê . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

32

§1.10.1 Ă„ Ÿê ^{ . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

32

§1.10.2 ĂŤĂŞÂ‡ĂŞÂŒĂ€§Íêk%@Š . . . . . . . . . . . . . . . . . . . . . .

33

§1.10.3 UCŸêÍêDŠ^S . . . . . . . . . . . . . . . . . . . . . . . . . .

34

§1.10.4 Â‡ĂŞÂŒCĂŤĂŞ . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

34

§1.10.5 Doc String Ÿê£ã . . . . . . . . . . . . . . . . . . . . . . . . . . .

36

§1.10.6 lambdaŸê . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

36

§1.10.7 Ÿê Š^Â?(scope) . . . . . . . . . . . . . . . . . . . . . . . . . . .

37

§1.10.8 i@Ÿê(nested) . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

38

§1.10.9 function ÍêD4 . . . . . . . . . . . . . . . . . . . . . . . . . . . .

38

§1.11 ÂŹ(module)ĂšÂ?(package) . . . . . . . . . . . . . . . . . . . . . . . . . . .

39

§1.11.1 MĂŻÂ˜Â‡module . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

39

§1.11.2 No Êmodule . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

41

§1.11.3 package(�) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

42

§1.12 name space(¡œÂ˜m) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

42

§1.13 a . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

46

§1.13.1 Â&#x;o´object . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

46

§1.13.2 Â&#x;o´class oject . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

48

§1.13.3 property Ăšmethord . . . . . . . . . . . . . . . . . . . . . . . . . . . .

50

§1.13.4 bound methord Ăšunbound methord . . . . . . . . . . . . . . . . . .

52

§1.13.5 U(inherit) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

54

§1.13.6 ¡ ¤ CÞ . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

54

§1.13.7

Abstrace Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

55

§1.13.8 hkattribute . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

55

§1.13.9 Python ¼class A� methord

. . . . . . . . . . . . . . . . . . . . .

56

§1.13.10 ˜ AĂ? ­1Ÿê ^{Ăž~ . . . . . . . . . . . . . . . . . . . .

63

§1.13.11 new style class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

75

§1.14 É~?n(exception) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

82

§1.14.1 Â&#x;o´Ă‰~?n§Â?Â&#x;o‡kÉ~?n . . . . . . . . . . . . . . . . .

82

§1.14.2 Ă“Âźexception(É~) . . . . . . . . . . . . . . . . . . . . . . . . . . .

84

§1.14.3 Ă‘exception . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

88

annCharles@tom.com

1iiÂ?, 208Â?

Python ÆS)P


8ยน 1 ร mu Python ยฆ^ รณรค

91

ยง2.1 ยฆ^Emacs ?6Python ยงS . . . . . . . . . . . . . . . . . . . . . . . . . . .

91

ยง2.1.1 SCpython mode . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

91

ยง2.1.2 python mode ร A5 . . . . . . . . . . . . . . . . . . . . . . . . .

92

ยง2.1.3 ~^รตUร ~ . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

92

ยง2.2 ร ยฆ?6รฌ . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

94

ยง2.3 Nร ยงS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

95

ยง2.3.1 ยฆ^DDD ร pydb Nร python ยงS . . . . . . . . . . . . . . . . . . . .

95

1n ร Python ~^ ยฌ

96

ยง3.1 Sย ยฌ . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

96

ยง3.1.1 ~^ยผรช . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

96

ยง3.1.2 a.=ย ยผรช . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

98

ยง3.1.3 ^uย 1ยงS Sย ยผรช . . . . . . . . . . . . . . . . . . . . . . . . . 100 ยง3.2 ร รถย Xร ย ' N^ . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 103 ยง3.2.1 ย mยฉย . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 106 ยง3.2.2 ร ยฉย . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 106 ยง3.2.3 '4ยฉย . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 107 ยง3.3 regular expression . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 107 ยง3.3.1 {รผ regexp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 108 ยง3.3.2 iร 8ร . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 108 ยง3.3.3 ยญE . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 110 ยง3.3.4 ยฆ^ ยฉiร G

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 110

ยง3.3.5 ยฆ^re ยฌ . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 110 ยง3.3.6 p?regexp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 112 ยง3.3.7 ยฉ|(Group) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 113 ยง3.3.8 Compile Flag . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 115 ยง3.4 ^struct ยฌ?n ?ย รชรข . . . . . . . . . . . . . . . . . . . . . . . . . . . 116 ยง3.5 ^Cmd ยฌ? {รผ ยท-1 ย . . . . . . . . . . . . . . . . . . . . . . . . 118 ยง3.5.1 {รผ ~f . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 119 ยง3.5.2 ยฝร %@ยท- . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 120 ยง3.5.3 ?nEOF . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 120 annCharles@tom.com

1iiiย , 208ย

Python ร S)P


8¹ §3.5.4 ?n ·- . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 121 §3.5.5 ·-1gÄÖà

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 121

§3.5.6 UCIOÑ\ÑÑ . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 121 §3.5.7 UCJ«Î . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 122 §3.5.8 Jø3 ÏõU . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 122 §3.5.9 $1Shell õU . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 123 §3.5.10

getattr õU ¦^ . . . . . . . . . . . . . . . . . . . . . . . . . . . . 123

§3.6 ?n·-1À

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 124

§3.6.1 {ü ~f

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 124

§3.6.2 këê ·-1À . . . . . . . . . . . . . . . . . . . . . . . . . . . 125 §3.6.3

optparser ¬ . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 126

§3.7 'u m ¬

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 136

§3.8 socket ?§ . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 136 §3.8.1 0 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 136 §3.8.2 {ü ~f . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 138 §3.8.3 Mïsocket

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 139

§3.8.4 ½socket

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 140

§3.8.5 ïáë . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 141 §3.8.6 Âxêâ . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 141 §3.8.7 ämë . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 142 §3.8.8 Ù¦9ϼê . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 143 §3.8.9

TCP ÚUDP «O . . . . . . . . . . . . . . . . . . . . . . . . . . . . 145

§3.8.10 'uTCP ÑÖì {K . . . . . . . . . . . . . . . . . . . . . . . . . 146 §3.9 Âe . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 150 §3.10 POP3 Æ0 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 150 §3.10.1 {ü ~f . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 150 §3.10.2 ¦^POP3 Æ Âe . . . . . . . . . . . . . . . . . . . . . . . . . 151 §3.10.3 õ1 A ?n . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 151 §3.10.4 POP3Ï&L§¥ G . . . . . . . . . . . . . . . . . . . . . . . . . 152 §3.10.5 POP3¥ ·- . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 152 §3.11 ^poplib ¬Â e . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 158 annCharles@tom.com

1iv , 208

Python ÆS)P


8¹ §3.12 SMTP Æ0 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 160 §3.12.1 SMTP ~f . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 160 §3.12.2 uxe ·- . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 162 §3.12.3 Ù¦·- . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 164 §3.12.4 ESMTP . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 166 §3.12.5 ¹@y . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 166 1o Ù Tkinter ?§

167

§4.1 Tkinter0 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 167 §4.1.1 o´Tkinter . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 167 §4.2

Hello Tkinter §S . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 168 §4.2.1 {ü ~f . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 168 §4.2.2 , {ü§S

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 170

§4.3 Widget . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 171 §4.4 Geometry Manager(AÛ+nì) . . . . . . . . . . . . . . . . . . . . . . . . . 172 §4.4.1 Pack +nì . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 173 §4.4.2 Grid +nì . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 176 §4.5 Widget ª . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 178 §4.5.1 ôÚ . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 178 §4.5.2 iN . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 179 §4.5.3 ©i ªz . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 182 §4.5.4 >µ . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 182 §4.5.5 àI . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 184 §4.6 ¯ Ú¯ ½ . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 186 §4.6.1 {ü ~f

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 186

§4.6.2 ¯ ?n¼ê . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 188 §4.6.3 ¯

g . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 188

§4.6.4 Ó ¯ õ ?n¼ê . . . . . . . . . . . . . . . . . . . . . . . . 191 §4.6.5 ÚWM ' ¯ ½ . . . . . . . . . . . . . . . . . . . . . . . . . . 192 §4.7 ~^ A^§S¦^ Widget . . . . . . . . . . . . . . . . . . . . . . . . . . . 193 §4.7.1 Ä I . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 193 §4.7.2 èü . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 193 annCharles@tom.com

1v , 208

Python ÆS)P


8ยน ยง4.7.3 รณรค9 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 197 ยง4.7.4 G 9 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 197 ยง4.7.5 IOรฉ{ยต . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 199 1 ร ร Python * ร

205

ยง5.1 ^C? *ร ยฌ . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 205

annCharles@tom.com

1viย , 208ย

Python ร S)P


ĂŁ

ĂŁ 3-1 žmŸêƒm 'X . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 137 3-2 Â?rà ÚÑÖÏà ŸêN^6§ . . . . . . . . . . . . . . . . . . . . . . . . 139 4-1 Tkinter XĂš

gĂŁ . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 167

4-2 hello1.py $1(J . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 169 4-3 hello2.py $1(J . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 171 4-4 border1.py $1(J . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 183 4-5 cursor1.py $1(J . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 185 4-6 menubar2.py $1(J . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 194 4-7 menubar3.py $1(J . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 196 4-8 toolbar1.py $1(J . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 198 4-9 statusbar1.py $1(J . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 199 4-10 inputpassword.py $1(J . . . . . . . . . . . . . . . . . . . . . . . . . . . 203

annCharles@tom.com

1viiÂ?, 208Â?

Python ÆS)P


L‚

L‚ 1.5-1 iÎG¼ =¿iÎ . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

14

1.5-2 iÎG=†�ٌa. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

14

1.5-3 äiĂŽG´Ă„ĂĄu,ÂŤaO Ÿê . . . . . . . . . . . . . . . . . . . . . .

16

1.13-4 ÂŒ¹­1 ÂŽâ܊Οê . . . . . . . . . . . . . . . . . . . . . . . . . . .

63

3.1-1 Python ­^S˜Ÿê . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

97

3.1-2 a.=†Ÿê . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

99

3.2-3 XĂšN^Ăž~ . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 103 3.4-4 struct ÂŹÂĽ ‚ª½Ă‚ . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 117 3.4-5 i!^S½Ă‚ . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 118 3.5-6 ¡-1?6 ÂŻ$Â… . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 119 3.7-7 Lžm . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 137 3.8-8 ^u=†i!^S Ÿê . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 145 3.8-9 TCP ĂšUDP ÂŤO . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 146 3.11-10 poplib ¡-o( . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 160 4.5-1 tkFont |Âą option . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 181 4.6-2 ¯‡£ãÞ~ . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 189 4.6-3 £ã¯‡ ĂŤĂŞ . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 189

annCharles@tom.com

1viiiÂ?, 208Â?

Python ÆS)P


1 Ù

Python0 0 python´ «)º5 ¡ é ó"pythonk±eA:" )º . Ý ú§mu±Ïá§NÁN´§g·*Ð5"dukeval õU§? §S ±3$1 UYmu"ù´éõ)º. ó 5"XVB kScript Engineer§LispkEVAL§ Emacs r *Ð5" ¡ é 3Python¥§a(class)§¼ê(function)§ ¬(module) Ñ´é "§Ü `§¦'Java§C++ \OO( Object Oriented)"O4·ò\“ o OO? Java OO?” ?Ø¥§^LÒ "z óÑk g `":§ Python á õ ó `:" * Ð Python ¦^C ó §ég, ^C½öC++ ó*ÐPython A5"X? # ¬§O\# êâa. " i \ Python )ºìÚ ±éN´ i\ ^rgC C½öC++ ó§S 8 ¥ § ¦ \ § S ± | ± ? § § * Ð õ U " y 3 Ò kPython ¬ ± * ÐVIMÚEmacs õU" S Ø Python Ø%)ºì´é " Ä a. ØI ¯k(²(declare)Cþ a.§ ¦^CþÒ éõÙ¦)º. óVB§VB Script§JScript§PERL " ra . ¦+CþØ^(²(declare)a.§ ´ Cþk §@où ´k a. "ØUòstringa. Cþ D integera. Cþ§ ´I a.= " ùÚVB§VBScript§JScript§PERLØ §ÚJava " annCharles@tom.com

11 , 208

Python ÆS)P


˜ Python0

§1.1 mŠ §1.1.1 XĂ›$1Python§S Python ´ ˜ ÂŤ ) Âş . ? § Š Ăł § Ăš Ă™ ÂŚ ) Âş . ? § Š Ăł § XPerl§VB§Bash§Awk§Sed Ă‘kaq §$1Â?{Xe" • 1Â˜ÂŤÂ?{´ pÂŞ"b \´3Unix ‚¸e§$ ´¡-1JÂŤĂŽĂ’" $python Python 2.2 (#1, Apr 12 2002, 15:29:57) [GCC 2.96 20000731 (Red Hat Linux 7.2 2.96-109)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> print "Hello World" Hello World >>> #U CTRL+D òĂ‘ 3Windows ÂĽÂ?kaq ‚¸" Š¼ÂŒþê~fĂ‘´3 pÂŞ$1 ">>>Ăš...L ÂŤPython JÂŤĂŽĂ’"Bash e Êþ¡-1?6¡-Ă‘´ÂŒ¹Œ^ §XC-a §C-e §C-w §Ă?Â?Œ‚Ñ´Œ^readline ÂĽ" • Â„ÂŒÂąr§S 3˜‡ŠÂ‡¼§^python )ºÏN^" $cat test.py print "Hello World" $python test.py Hello World $cat test.py | python #+ ܊ Hello World $python < test.py #Ă‘\­½Â• Hello World • r§SŠÂ?Â˜Â‡ÂŒÂą$1 Unix ŠÂ‡" $cat test.py #!/usr/bin/python print "Hello World" $ls -l test.py -rw-r--r-1 chunywan mnw $chmod +x test.py $ls -l test.py annCharles@tom.com

12Â?, 208Â?

40 Sep 12 13:34 test.py

Python ÆS)P


§1.2 ˜ƒ Â?ʖ -rwxr-xr-x $./test.py Hello World

1 chunywan mnw

40 Sep 12 13:34 test.py

5Âż 1˜1 AĂ?5ºŠʧڴUnix eĂ?^ Â?{"Perl§Tl/Tcl§Sed§awk§Bash Ă‘´Úo^ " Š 5Âż ´5ºŠʧ# ÂĄLÂŤ5Âş"Ăšbash˜ "5ºŠÊ3Nà §S žÿ§ ´Êk^ §Â„ÂŒÂąJp§S ÂŒĂ–5"

§1.2 ˜ƒ Â?ʖ a(class)§Ÿê(function)§ ÂŹ(module) Ă‘´Ê–"â€œÂ˜ÂƒĂ‘´Ê–§Ê–ÑkÂś iâ€?§Ú´¡ ˜‡o("

§1.3 Ă„ a. §1.3.1 .(integer) wĂĽ5” ĂŞ LÂˆÂŞĂ’´ ."kÂąe$ÂŽ ܊Î

¿Â

~f

(J

+ − ∗ / % ∗∗ divmod

\{ ~{ ÂŚ{ Ă˜{ ˜ Ă˜{

1+1 1-1 2*10 10/3 10/3 2**4 divmod(10§3)

2 0 20 3 1 16 (3§1)

§1.3.2 2:.(float) wĂĽ5”2:ĂŞ LÂˆÂŞĂ’´2:ĂŞ"Ăš .aq"5¿§1´ .§1.0´2:."Ăœ 6LÂˆÂŞ1 == 1.0 ´ýŠ"5¿§2:ĂŞ $ÂŽ´kĂ˜ "^u‰ÆOÂŽ žÿ§I‡ ٌ ÂŹ|Âą"Ú´Ă?Â?2:$ÂŽĂŹ Â?ULÂŤk  ê"

§1.3.3 Nonea. None´Â˜Â‡AĂ? ~Þ§LÑ†"3Âą

ÂŒÂąw ÂŚ ^?"

§1.3.4 Ăœ6LÂˆÂŞ PythonÂĽvkbooleana."ҔCŠó¼§Ă˜ 0Âą §Ă™ÂŚĂ‘´ý" ´PythonÂĽ “bâ€?kÊþ§Â?) annCharles@tom.com

13Â?, 208Â?

Python ÆS)P


˜ Python0 None,0,0.0,"" (˜iĂŽG),[](˜list),()(˜tuple),{}(˜dictionary) PythonÂĽkÂąeĂœ6$ÂŽĂŽ" and or not

Ăœ6† Ăœ6½ Ăœ6‡

>>> def getTrue(): ... print "debug: true" ... return 1 ... >>> def getFalse(): ... print "debug: false" ... return 0 ... >>> if getTrue() and getFalse(): ... print "ok" ... else: ... print "bad" ... debug: true # k$1 getTrue debug: false # XJ getTrue ÂˆÂŁĂ˝,@o$1getFalse bad # ‡(J´ getFalse ÂˆÂŁ(J. >>> if getFalse() and getTrue(): ... print "ok" ... else: ... print "bad" ... debug: false #k$1 getFalse bad #XJ getFalse ÂˆÂŁb,@oĂ’Ă˜$1 getTrue >>> Š 5Âż ´and Ăšor §Êuand 5`§~Xexpr1 and expr2§XJexpr1 ´Ăœ6b§@ oĂ’o LÂˆÂŞÂ† ÂˆÂŁexpr1 §Â?N´Â˜iĂŽG§½Ü˜list§ Ă˜2OÂŽexpr2§Â?Ă’´ `expr2 ÂĽXJkŸêN^ {§Â?Ă˜ÂŹÂ‰1"XJexpr1 ´Ăœ6ý§@oâOÂŽexpr2 § Â‡Ăœ6LÂˆÂŞĂ’ÂˆÂŁexpr2"ĂŠuor 5`§~Xexpr1 or expr2§XJexpr1 ´Ăœ6 ý§@oĂ’o LÂˆÂŞÂ† ÂˆÂŁexpr1 § Ă˜2OÂŽexpr2§Â?Ă’´`expr2 ÂĽXJkŸê N^ {§Â?Ă˜ÂŹÂ‰1"XJexpr1 ´Ăœ6b§@oâOÂŽexpr2 § Â‡Ăœ6LÂˆÂŞĂ’Âˆ ÂŁexpr2"Ăš Ă’kÂ˜ÂŤ~^ AĂ?LˆÂ?ÂŞ: annCharles@tom.com

14Â?, 208Â?

Python ÆS)P


§1.3 Ă„ a. <cond> and <expr_true> or <expr_false> ÂŚkÂ˜Â‡ĂŠk^ ŠÂ´: XJcond ¤å§@oÂˆÂŁexpr_true§Ă„KÂˆÂŁexpr_false" ÂŚvkŠ‡Â&#x;o5K§Â?´l† mÂ?g"4¡Â‚5u ˜eÂ?Â&#x;o: cond

expr_true

expr_false

o (J

Ă˝

Ă˝

?Ă›(Ă˜OÂŽ)

expr_true

b b

?Ă›(Ă˜OÂŽ) ?Ă›(Ă˜OÂŽ)

Ă˝ b

expr_false expr_false

Ă˝ Ă˝

b b

b Ă˝

expr_false expr_false

lڇLĂžÂŒÂąw : • ĂžÂ˜|`² §XJcond ´ý§@o ‡LÂˆÂŞĂ’´expr_true • 1 |`² §XJcond ´b§@o ‡LÂˆÂŞĂ’´expr_false •  Â˜|`² §¡`Âœ "P4XJexpr_true kÂŒU´b žÿ§Ă˜Â‡Ăšo‰§ Ă?Â?kÂŒU‹ 5 ŠÂ§cond ´ý žÿ§ ‡LÂˆÂŞ%´expr_false")Ăť ڇ¯K Â?{Ă’´: (<cond> and (<expr_true>,) or (<expr_false>,))[0]  ¥ )Ă’r ‡LÂˆÂŞ)ĂĽ5§UCOÂŽ`k?§Ă„K[0] `k? p"ÂĽm )Ă’ĂšĂ?Ă’§´Â˜Â‡tuple LÂˆÂŞ"Ăš (<expr_true>,)[ ´ý§Ă?Â?Œ´š k˜‡ ƒ tuple§ [0] LÂŤJ Ñڇ ƒ5"3$ ´§Ă?~ڇLˆ ª´^3' {Ăź Âœše§{Ăź DŠŠʧexpr_trueĂšexpr_false Â˜Â„Ă‘´~ Þ§ Â…´ý" >>> x= cond and "OK" or "BAD" >>> x ’OK’ >>> cond = 0 >>> x= cond and "OK" or "BAD" >>> x ’BAD’ >>> Ă“ n: <cond> or <expr_false> and <expr_true> Â?kaq ŠÂ§ ´Ă˜Â‡ ÂŚ^ڍLˆÂ?ª§Ă˜´Ă?Â?ڇLÂˆÂŞĂ˜Ăœ{§ ´Ă? Â?ÂŚĂ˜ĂŽĂœS."?§ÂŠĂłĂšg,Šókaq /Â?§Ă’–¡Â‚²ÂžÂŹ`§â€œr§¯ÂŒ â€?§ annCharles@tom.com

15Â?, 208Â?

Python ÆS)P


˜ Python0 ´¡Â‚Ă˜ÂŹ`§â€œr§?ĂŞ â€?§½Ü“r§? â€?§Ă˜´Ă?Â?@o`Ă’´Â† §´Ă?Â?Ă˜ ĂœS."@Ă’¯§Â?Â&#x;oĂ˜ĂœS.§S.l=p5Âş Ă?´lC Šó¼5"C Šó¼k cond ? true_expr: false_expr ڴ˜‡n ܊Χ¯þ C Šó ÂŚ^Ăś^ A›c §Ăš1Â˜ÂŤÂŠĂ‚´aq " oƒ§# ÂĄ@ÂŤÂ?ª§Â? 1Â˜ÂŤĂ’Ă? "

§1.4 L(list) list aquC++ÂĽ vector§C Šó¼ ĂŞ|§^u ;^S( "X§ ˜cÂĽz‡ Uê§ÂŒÂąLÂŤÂ? [ 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 ] ˜cÂĽz‡ œ¥§ÂŒÂąLÂŤÂ? [ ’January’, ’February’, ’March’, ’April’, ’May’, ’June’, ’July’, ’August’, ’September’, ’October’, ’November’, ’December’ ] z‡(Ă? Âśi§ÂŒÂąLÂŤÂ? [ ’Monday’,’Tuesday’, ’Wednesday’, ’Thursday’ , ’Friday’, ’Saturday’, ’Sunday’]

§1.4.1 MĂŻlist a=[’1’,’2’] ^[])ĂĽ5§LÂŤÂ˜Â‡list§¼m ˆ‡ ƒŒ¹´?Ă›a.§^Ă?Ă’ŠÂ…"

§1.4.2 list eIĂšflist list eIl0mŠ§ĂšCŠóaq§ ´O\ KeI ÂŚ^" -len ... -2 -1 0 1 ... len-1

1˜‡ ƒ ... ĂŞ1 ‡ ƒ  ˜‡ ƒ 1˜‡ ƒ 1 ‡ ƒ ...  ˜‡ ƒ

>>> a=[0,1,2,3,4,5,6] annCharles@tom.com

16Â?, 208Â?

Python ÆS)P


§1.4 L(list) >>> i=-len(a) >>> while i < len(a): ... print "a[",i,"]=",a[i] ... i=i+1 ... a[ -7 ]= 0 a[ -6 ]= 1 a[ -5 ]= 2 a[ -4 ]= 3 a[ -3 ]= 4 a[ -2 ]= 5 a[ -1 ]= 6 a[ 0 ]= 0 a[ 1 ]= 1 a[ 2 ]= 2 a[ 3 ]= 3 a[ 4 ]= 4 a[ 5 ]= 5 a[ 6 ]= 6 5ÂżwhileŠÊ  ?"ÂŹ3 >>> a[-8] Traceback (most recent File "<stdin>", line IndexError: list index >>> a[7] Traceback (most recent File "<stdin>", line IndexError: list index

¥0 "a[-8] Úa[9] яÚü ."

call last): 1, in ? out of range call last): 1, in ? out of range

§1.4.3 flist J ÂŒĂ?LeIÂ?½Â‰ÂŒ§^uJ Ă‘Â˜Â‡list Â˜ĂœŠ"eIL² Â˜§Â˜Â‡üŠ Â˜§ ˜‡(ĂĽÂ Â˜§¼m^kĂ’ŠÂ…"XJĂ˜Â?½üŠ Â˜§üŠ Â˜´0 §XJĂ˜Â?½(ĂĽÂ Â˜§(ĂĽÂ Â˜´âˆ’1"flist LÂŤÂ?)üŠ Â˜? ƒ§Â˜Â— (ĂĽÂ Â˜§ ´Ă˜Â?)(ĂĽ  Â˜ ƒ" KeIÂ?ÂŒ¹Í†½Ă‚üŠ Â˜§½Ü(ĂĽÂ Â˜" >>> a[1:4] annCharles@tom.com

17Â?, 208Â?

Python ÆS)P


˜ Python0 [1, >>> [0, >>> [1, >>> [0, >>> [0, >>> [1,

2, 3] a[:] 1, 2, 3, a[1:] 2, 3, 4, a[:3] 1, 2] a[:] 1, 2, 3, a[1:-1] 2, 3, 4,

4, 5, 6] 5, 6]

4, 5, 6] 5]

flist ´ 5list ˜‡€ §Â˜Â‡B §UCflist Ă˜ÂŹUC 5 list"

§1.4.4 ?nlist Â?{ • L.append(var) §J\ ƒ" >>> >>> >>> [0, >>>

a=[0,1,2,3,4,5] a.append(6) a 1, 2, 3, 4, 5, 6]

• L.count(var) OÂŽvar 3LÂĽĂ‘y gĂŞ" >>> a=[0,2,2,2,3,3] >>> a.count(2) 3 >>> a.count(3) 2 • len(L) ÂˆÂŁL Ă?" >>> a=[1,2,3] >>> len(a) 3 • L.extend(list) §òlistJ\3L

ÂĄ"

>>> a=[1,2,3] >>> a.extend([4,5,6]) annCharles@tom.com

18Â?, 208Â?

Python ÆS)P


§1.4 L(list) >>> a [1, 2, 3, 4, 5, 6] • L.index(var) ÂˆÂŁvar3LÂĽ  Â˜§eĂƒ§K ÑÉ~" >>> a=[1,2,3,4,4,5] >>> a.index(4) 3 >>> a.index(6) Traceback (most recent call last): File "<stdin>", line 1, in ? ValueError: list.index(x): x not in list • L.insert(index,var) 3index?§ \var§Ă™{ ĥ Ă­"XJindexÂŒulist Ă?§Ă’3 V\"XJindex u0§Ă’3 mŠ?V\" >>> >>> >>> [1, >>> >>> [1, >>> >>> [1,

a=[1,2] a.insert(0,1) a 1, 2] a.insert(100,100) a 1, 2, 100] a.insert(2,3) a 1, 3, 2, 100]

• L.pop() ÂˆÂŁÂ Â˜Â‡ ƒ§¿Â…Ă­Ă˜ Âƒ§¿Â…Ă­Ă˜T ƒ" >>> >>> 3 >>> 0 >>> [1, >>>

˜‡ ƒ"L.pop(index) ÂˆÂŁindex?

a=[0,1,2,3,] a.pop() a.pop(0) a 2]

• L.remove(var) ĂŠ var§¿Â…Ă­Ă˜Âƒ§eĂƒ§ ÑÉ~" annCharles@tom.com

19Â?, 208Â?

Python ÆS)P


˜ Python0 >>> a=["a","b","a","c","a","d"] >>> a.remove("a") >>> a [’b’, ’a’, ’c’, ’a’, ’d’] >>> a.remove("a") >>> a [’b’, ’c’, ’a’, ’d’] • L.reverse() òL S" >>> >>> >>> [5,

a=[1,2,3,4,5] a.reverse() a 4, 3, 2, 1]

• L.sort() §òaĂźS§aÂĽ ƒea.Ă˜Ă“§(JgCw˜wj"Â˜Â„Ă˜ÂŹĂšo‰"Q ,\Ă‘Ă˜(½listÂĽ ƒ a.´Ă„˜ §\„‡ßS§@o\Ă?–´Â&#x;o(J? >>> >>> [1, >>> >>> >>> [1,

a.sort() a 2, 3, 4, 5] a=[1,"abc",2,"xxx"] a.sort() a 2, ’abc’, ’xxx’]

L.sort(func) §ò^funcŠÂ?' Ÿê§òßS"func(x,y)§ÂˆÂŁâˆ’1§0§1ŠOL ÂŤ u§ u§ÂŒu"

§1.4.5 ^list [ٌ~^êâ( ^list [ĂŚĂ’stack >>> >>> >>> >>> >>> [0, >>> 2

a=[] a.append(0) #Ă˜Ă’ a.append(1) a.append(2) a 1, 2] a.pop() #Ă‘Ă’

annCharles@tom.com

110Â?, 208Â?

Python ÆS)P


§1.4 L(list) >>> a.pop() 1 >>> a.pop() 0 >>> ^list [è queue >>> >>> >>> >>> [2, >>> 0 >>> 1 >>> 2 >>> []

a.insert(-1,0) #\è a.insert(-1,1) a.insert(-1,2) a 1, 0] a.pop() #Ă‘è a.pop() a.pop() a

½Ü >>> >>> >>> >>> >>> [0, >>> 0 >>> 1 >>> 2 >>> 3

a.append(0) a.append(1) a.append(2) a.append(3) a 1, 2, 3] a.pop(0) a.pop(0) a.pop(0) a.pop(0)

annCharles@tom.com

111Â?, 208Â?

Python ÆS)P


˜ Python0 ^list [ätree >>> leaf1=[0,1] >>> leaf2=[2,3] >>> leaf3=[4,5] >>> leaf4=[6,7] >>> branch1=[leaf1,leaf2] >>> branch2=[leaf3,leaf4] >>> root=[branch1,branch2] >>> root [[[0, 1], [2, 3]], [[4, 5], [6, 7]]]

§1.4.6 list comprehension Š{: [ <expr1> for k in L if <expr2> ] ŠÂ: returnList=[] for k in L: if <expr2>: returnList.append(<expr1>) return returnList; ÂˆÂŁÂ˜Â‡list§list ƒdz˜‡expr1 |¤§if ŠÊ^uLĂˆ§ÂŒkÂŒĂƒ" >>> a=["123","456","abc","Abc","AAA"] >>> [ k.center(9) for k in a ] [’ 123 ’, ’ 456 ’, ’ abc ’, ’ Abc # aÂĽ=di1|¤ iĂŽG§¿rÂŚC¤ÂŒ " >>> [ k.upper() for k in a if k.isalpha() ] [’ABC’, ’ABC’, ’AAA’] # aÂĽ=dÂŒ i1|¤ iĂŽG§¿rÂŚC¤ " >>> [ k.lower() for k in a if k.isupper() ] [’aaa’] # aÂĽ=kĂŞi ¤ iĂŽG§¿rÂŚC¤ ĂŞa." >>> [ int(k) for k in a if k.isdigit() ] [123, 456]

’, ’

AAA

’]

LĂˆ(filter)§ĂšN (mapping)Ăš Â?˜" ÂŚ+ڇ^{ĂŠ{ߧ ´%›Šk^§§SC {'§ÂŒĂ–5r"kÊþžÿ§¡Â‚ ÂŚ^ĂŒÂ‚ÂŠʧ==‰Ê{Ăź ÂŻÂœ§ ´ĂŒÂ‚ŠÊ ´ÊĂ˜Ă?Ă– §Ă?Â?ĂŒÂ‚ÂŠĂŠĂ˜ĂŽ annCharles@tom.com

112Â?, 208Â?

Python ÆS)P


§1.5 iĂŽG(string) Ăœg,Šó¼ S."~X¾Þ¥ ~f¼§k˜‡LÂŤâ€œrlist ÂĽ z‡iĂŽGÂĽ iĂŽ C¤ÂŒ â€?" ´XJ^ĂŒÂ‚ÂŠĂŠLÂŤĂ’´: “MĂŻÂ˜Â‡Â˜list§Êulist ÂĽ z˜‡ ƒ§r ڇiĂŽGC¤ÂŒ §V\ #ĂŻ listÂĽ"â€? „kĂŠĂľ~f§4¡Â‚ĂŠg, A^ڍ^{" rlistÂĽ ¤k ƒ\ 1 [ k+1 for k in list] J Ă‘ list ¼¤k ĂŞCĂž [ k for k in list if type(k)==types.IntType] r list ÂĽ ¤k ĂŞ ƒO\˜ [ k + 1 for k in list if type(k)==types.IntType ] ¡Âš~U ÚLˆÂ?ÂŞÂœ

§1.5 iĂŽG(string) §1.5.1 iĂŽG LÂŤ ^ßÚÒ½VÚÒ ¤iĂŽG ’hello’ "world" k˜ iĂŽ´Ăƒ{^Â… Ă‘\ §¤¹^iĂŽ|ĂœLÂŤAĂ?iĂŽ"XL1.5-1" Ú´ĂšC Šó›Šaq §Â„kecho ¡-§Java ŠóÑ´ÚoLÂŤÂ˜Â‡AĂ?iĂŽ " XJ‡Ñ\˜‡›Š iĂŽG§Â˜1Ă˜Â?B§Ă’^Ăź1"߇iĂŽGÂĽmd˜xiĂŽ ĂŤ §LÂŤÂ˜Â‡iĂŽG"X "abc" \ ’def’ LÂŤâ€œabcdefâ€?§5¿Ú"abc"+"def"´kÂŤO §Â‘+ Lß‡iĂŽGĂŤ ˜ü§^˜ xiĂŽĂŤ §LÂŤÂ˜Â‡iĂŽG" XJ‡Ñ\˜‡›ŠÂ›Š iĂŽG§Ă’^n‡ÍY VÚÒG"X """ this is a very very long string. And it contains a lot line. it is suitable to write document of function. """ annCharles@tom.com

113Â?, 208Â?

Python ÆS)P


˜ Python0 LÂŤ iĂŽ

¿Â

5

\newline

Ăƒ

Ă‘

^uĂŤ þ‡å 1§ ¤Â˜Â‡ 1

\\ \’ \" \a \b \f \n \N{name} \r \t \v \u{xxxx} \ooo \xhh

\ ’ " 0x07 0x08 0x0c 0x0a

“è

0x0d 0x09 0x0b 0xooo 0xhh

‡ m ßÚÒ VÚÒ Â?$ ò‚ Formfeed (FF) †1 Unicode iĂŽ ÂŁÂ? Y²Â›LĂŽ R†›LĂŽ Unicode?è ooo LÂŤ l?›iĂŽ hh LÂŤ ›8?›iĂŽ

ASCII ››iÎ ASCII ››iÎ ASCII ››iÎ ASCII ››iÎ � ÊuUnicode ASCII ››iÎ

Â? ĂŠuUnicode

L 1.5-1: iĂŽGÂĽ =ÂżiĂŽ ِϴ

ĂľU

~f

(J

float(str) int(str) int(str,base) long(str) long(str,base)

C¤2:ĂŞ C¤ . C¤base?› ĂŞ C¤ . C¤base?› ĂŞ

float("1e-1") int("12") int("11",2) int("12") int("11",2)

0.1 12 2 12 2

L 1.5-2: iÎG=†�ٌa.

§1.5.2 =†¤Â?ٌa. §1.5.3 iĂŽG ܊ ĂŠ ߇iĂŽG >>> "Hello" + " " + "World" ’Hello World’ ÂŒ =† >>> "this is test".capitalize() #Ă„i1ÂŒ annCharles@tom.com

114Â?, 208Â?

Python ÆS)P


§1.5 iĂŽG(string) ’This is test’ >>> "THIS IS TEST".capitalize() ’This is test’ >>> "THIS IS TEST".lower() # ĂœC¤ ’this is test’ >>> "this is test".upper() # ĂœC¤ÂŒ ’THIS IS TEST’ >>> "This Is Test".swapcase() #ÂŒ p† ’tHIS iS tEST’ iĂŽG Ă? >>> len("Hello World") 11 iĂŽG fG ÂŒÂąr˜‡iĂŽGw¤Â˜Â‡škĂŠĂľiĂŽ list§Ú ÂŒÂą^ĂšlistÂƒĂ“ Â?ÂŞ f G"eIl0mŠ"Kê“L‡•" >>> str="Hello World" >>> str="Hello" >>> i=-len(str) >>> while i < len(str): ... print "str[",i,"]=",str[i] ... i=i+1 ... str[ -5 ]= H str[ -4 ]= e str[ -3 ]= l str[ -2 ]= l str[ -1 ]= o str[ 0 ]= H str[ 1 ]= e str[ 2 ]= l str[ 3 ]= l str[ 4 ]= o >>> kĂ’ÂŒÂąLÂŤÂ‰ÂŒ§ fiĂŽG"kĂ’Ăź> ĂŞLÂŤe.ÚÞ.§e.ÚÞ.Ă‘´ÂŒĂ€§ "ÂŽĂž3Â?-1§e.Â?0" annCharles@tom.com

115Â?, 208Â?

Python ÆS)P


˜ Python0 >>> str="Hello" >>> str[:] ’Hello’ >>> str[1:2] ’e’ >>> str[1:-1] ’ell’ >>> str[-1:2] ’’ Ke.Â?´Â“L Â˜§Ă˜Â“LÂŒ "¤¹lڇ¿ÂÞڧ−1 ‡'2 ÂŒ"str[-1:2]´Â˜ iĂŽG"AT5¿ŒfiĂŽG´ý 5 iĂŽG € §UC iĂŽG´Ă˜ÂŹUC 5 iĂŽG "Ă˜ÂŒÂą^fiĂŽG Â?ÂŞUC 5 iĂŽG"X: >>> a="abcd" >>> b=a[1:2] >>> b="x" #UC b >>> a ’abcd’ #Ă˜ÂŹKÂ? a >>> a[1]=’abc’ # Traceback (most recent call last): File "<stdin>", line 1, in ? TypeError: object doesn’t support item assignment >>> äiĂŽG´Ă„ĂĄu,ÂŤaO L1.5-3ÂĽ Â?{ÂŒÂą äiĂŽG¼´Ă„ĂŽĂœ, ^‡"iĂŽGáv^‡§Ă’ÂˆÂŁ1§Ă„ K§ÂˆÂŁ0" ϴ

^‡

s.isalnum() s.isalpha() s.isdigit() s.islower() s.isupper() s.istitle() s.isspace()

¤kiĂŽĂ‘´êi0123456789 ½Üi1A-Z§a-z ¤kiĂŽĂ‘´i1a-z ½ÜA-Z ¤kiĂŽĂ‘´êi0123456789 ¤kiĂŽĂ‘´ i1a-z ¤kiĂŽĂ‘´ÂŒ i1A-Z ¤kĂźcĂ‘´Ă„i1ÂŒ §Â”‡title ¤kiĂŽĂ‘´Â˜xiĂŽ\n,\t,\r,’ ’ L 1.5-3: äiĂŽG´Ă„ĂĄu,ÂŤaO Ÿê

annCharles@tom.com

116Â?, 208Â?

Python ÆS)P


§1.5 iĂŽG(string) 3iĂŽGÂĽ ĂŠfG • s.find(substring,[start [,end]]) XJĂŠ §Âˆ£¢ĂšÂŠ§L²´3= kĂŠ "XJĂŠĂ˜ §ÂˆÂŁâˆ’1 #ok ÂĄ abc§a mĂž Â˜Â? 3, >>> "ok abc abc abc".find("abc") 3 #l Â˜4Âą mŠ ĂŠ"ƒ u s[4:].find("abc") >>> "ok abc abc abc".find("abc",4) 7 #ƒ u s[4:9].find("abc") >>> "ok abc abc abc".find("abc",4,9) -1 #ƒ u s[4:10].find("abc") >>> "ok abc abc abc".find("abc",4,10) 7 • s.rfind(substring,[start [,end]]) Ăšfind()aq§ ´´Â‡Â• ĂŠ" >>> "ok abc abc abc".rfind("abc") 11 • s.index(substring,[start [,end]] Ăšfind()aq§ ´XJĂŠĂ˜ substring§Ă’ )˜‡ValueError É~"ߍÂ?ÂŞ Ă˜Ă“3uÂ†Ă˜?n Ă˜Ă“" >>> "ok abc abc abc".index("abc") 3 >>> "ok abc abc abc".index("abcd") Traceback (most recent call last): File "<stdin>", line 1, in ? ValueError: substring not found in string.index • s.rindex(substring,[start [,end]] Ăšs.index()aq"Ă˜Ă“Âƒ?3u´Â‡Â• ĂŠ" • s.count(substring,[start [,end]]) ÂˆÂŁĂŠ substring gĂŞ" >>> "ok abc abc abc".count("abc") 3 annCharles@tom.com

117Â?, 208Â?

Python ÆS)P


˜ Python0 ‚ªziĂŽG Ă„ ^ { ´ s % <tuple> §tuple L ÂŤ ˜ ‡ ĂŤ ĂŞ L § a q uCŠ Ăł ÂĽprintf§ rtuple ÂĽ z˜‡Š^iĂŽGL§LÂŤ ‚ªds 5(½" >>> print "%s’s height is %dcm"%("Charles",180) Charles’s height is 180cm 5Âż %s,%dĂšCŠó¼ printf´aq §âŠ ‰conversion specifier§(=†½Ă‚) y3X­?Ă˜conversion specifier"conversion specifier kÂąeAÂ‡ĂœŠ ¤§ %[<mapping key>][<conversion flag>][<Minimum field width>]| [<precision>][<lenght modifier>]<conversion type>| w X ĂŠ E , § Ă™ ¢ Â? ‡ ˜ ‡% ˜ ‡conversion typeĂ’ ÂŒ Âą " Ă™ ÂŚ Ă‘ ´ ÂŒ Ă€ "conversion typeXe: • d LÂŤkÎқ?› ĂŞ" >>> "%d and %d" % (-1,2) -1 and 2 • i Ă“d • o LÂŤĂƒĂŽĂ’l?ݐ" >>> "%o and %o" % (16,8) 20 and 10 • u LÂŤĂƒĂŽĂ’ ĂŞ" >>> "%u and %u" %(-10,10) ’4294967286 and 10’ 5Âżâˆ’10 )º¤Â?ĂƒĂŽĂ’ êžÿ§LÂŤÂ˜Â‡ĂŠÂŒ ĂŞ"Ú´Ă?Â?3OÂŽĂ…ÂĽ^ Ă–èLÂŤKê§KĂŞ  p ´1§3 )º¤Â?ĂƒĂŽĂ’ĂŞ žÿ§Ă’ÂŹĂŠÂŒ" • x LÂŤĂƒĂŽĂ’Â›8?›( ) >>> "%x and %x" % (100,200) ’64 and c8’ • X LÂŤĂƒĂŽĂ’Â›8?›(ÂŒ ) >>> "%X and %X" % (100,200) ’64 and C8’ annCharles@tom.com

118Â?, 208Â?

Python ÆS)P


§1.5 iĂŽG(string) • e 2:ê§Â‰Ă†LÂˆÂŞ{( ) >>> "%e and %e"%(-100,200) 2.000000e+02 • E 2:ê§Â‰Ă†LÂˆÂŞ{(ÂŒ ) >>> "%E and %E"%(-100,200) 2.000000E+02 • f LÂŤ2:ĂŞ >>> "%f and %f"%(-0.00001,200.0) ’-0.000010 and 200.000000’ • g LÂŤ2:ê§XJ´ u0.0001½ÜĂ˜ °Ă?§Ă’^‰ÆLÂŤ{" >>> "%g and %g"%(-0.00001,2000000.0) ’-1e-05 and 2e+06’ • c rASCII ĂŞLß‡iĂŽ >>> "%c and %c"%(67,68) ’C and D’ ÂŒ^uC ĂŞÂ?ASCIIiĂŽ • r LÂŤÂ˜Â‡iĂŽG§Ú‡iĂŽGÂŚ^repr() ÂˆÂŁÂŠ >>> "%r"%({"one":1,"two":2}) "{’two’: 2, ’one’: 1}" Ăšprint expr(obj) ‹<Ă‘5 J˜ " • s LÂŤÂ˜Â‡iĂŽG§Ú‡iĂŽGÂŚ^str()Ÿê ÂˆÂŁÂŠ >>> "%s"%({"one":1,"two":2}) "{’two’: 2, ’one’: 1}" Ăšprint str(obj) ‹<Ă‘5 J˜ " 5Âżstr Ăšexpr Ÿê Ă˜Ă“"str ´ Â˜Â‡ĂŠÂ– š ÂŞ ÂŁĂŁ"expr ´ ˜ ‡iĂŽG§´Â˜Â‡Ăœ{ Python LÂˆÂŞÂŠʧÂŒÂą ʖ " mapping key Š ^ ´ ^dictionary “ Otuple § ^mapping keyŠ Â?keyL ÂŤdictionaryÂĽ C Ăž " Ăš ‘ 5 Ă? ? ´ § J p § S ÂŒ Ă– 5 §%dĂš%(height)' § Ăś ÂŒĂ–5‡Ă?" Â…§Ă“ ˜‡CÞÑyĂźg¹Þ§3tuple¼Ò‡ Ăźg§ …‡5ÂżtupleÂĽ ƒ ^SĂšÂ‡ĂŞĂ˜Â‡Â†§^mapping key Â?ÂŞĂ’Ă?Ăľ " annCharles@tom.com

119Â?, 208Â?

Python ÆS)P


˜ Python0 >>> print "%s’s height is %d cm, %s’s weight is %d kg" % \ ... ("Charles",170,"Charles",70) Charles’s height is 170 cm, Charles’s weight is 70 kg >>> print "%(name)s’s height is %(height)d cm" \ ... ",%(name)s’s weight is %(weight)d kg" % \ ... {"name":"Charles","height":170,"weight":70} Charles’s height is 170 cm,Charles’s weight is 70 kg nameĂ‘ y Ăź g § 3mapping keyÂĽ § Ă’ Ă˜ ^ Ăź g § Â… ĂŤ ĂŞ ^ S Â? ÂŒ Âą ‘ B " Ăšlocals()Ÿêƒ Ăœ§kÂ?Ă? J§locals()ÂˆÂŁlocal name space (Ă›Ăœ¡œÂ˜ m) §´Â˜Â‡dictionary§Ă™ÂĽkey´CĂž œ¥§value´CĂž Š"globals()ÂˆÂŁglobal name space ( Ă›¡œÂ˜m) ĂšpÂ?އ~f"3 ÂĄ name space(¡œÂ˜m)kÂ?[0 " >>> def fun(a,b): ... print "a is %(a)d,b is %(b)d" %locals() ... >>> fun(1,2) a is 1,b is 2 minimum field width LÂŤÂ Ă?" >>> print "%10d,%10d"%(1,2) 1, 2 precision^5L°Ă?§Â?ĂŠ2:ĂŞkŠ^§Â‘ko ĂŠ\ ĂľU" >>> print "%10.2f,%10.2f"%(10.123456,20.126456) 10.12, 20.13 conversion flag ´Ê, a.üŠ^"#LÂŤ^alternate form§XJ´8?›§@oĂ’3 cÂĄ\0§XJ´Â›8?›Ò3cÂĄ\0x ½Ü0X Êٌa.Ă˜ĂĽÂŠ^" >>> print "%#x,%#X,%#o" %(16,16,16) 0x10,0X10,020 0 LÂŤ^0Ă– §ŒÂƒávminimum field width" >>> print "%010d,%010d"%(1,2) 0000000001,0000000002 -L†Êà §XJĂš0ӞŒ^@o0Ă’Ă˜ĂĽÂŠ^" >>> print "%-010d,%-010d"%(1,2) 1 ,2 §Â˜Â‡Â˜Â‚§LÂŤ0Ăš ĂŞcÂĄ\‡˜‚§KĂŞcÂĄ\-§ annCharles@tom.com

120Â?, 208Â?

Python ÆS)P


§1.5 iĂŽG(string) >>> print "% 10d,% 10d,% 10d"%(-1,2,-0) -1, 2, 0 + LÂŤwÂŤĂŽĂ’§ ĂŞwÂŤ+§KĂŞwÂŤ>>> print "%+10d,%+10d,%+10d"%(-1,2,0) -1, +2, +0 lenght modifier Ă‘" ٌ{Ăź ‚ªzĂľU • s.ljust(width) †Êà XJs Ă?vkwidth@o §Ă’3 Ă?Â?width iĂŽG"Ă„K iĂŽGs"

ÂĄĂ–Â˜Â‚§ ˜‡

>>> "Hello World".ljust(1) ’Hello World’ >>> "Hello World".ljust(12) ’Hello World ’ >>> "Hello World".ljust(16) ’Hello World ’ • s.rjust(width) mÊà چÊà aq" >>> "Hello World".rjust(16) ’ Hello World’ >>> "Hello World".rjust(1) ’Hello World’ • s.center(width) Ă˜ÂĽaq§3ĂźĂžĂ–Â˜Â‚§Œs Ă?Â?width§XJs Ă? 'widthÂŒ§@oÂ&#x;oÂ?Ă˜Â‰" >>> "Hello World".center(1) ’Hello World’ >>> "Hello World".center(16) ’ Hello World ’ • K ˜ x i ĂŽs.lstrip() K † > ˜ x i ĂŽs.rstrip() K m > ˜ x i ĂŽs.lstrip() KĂź> ˜xiĂŽ >>> "\t a ’a ’ >>> "\t a

\t".lstrip() \t".rstrip()

annCharles@tom.com

121Â?, 208Â?

Python ÆS)P


˜ Python0 ’ a’ >>> "\t a ’a’

\t".strip()

#‡ python 2.2.3ÂĽO\ Â˜Â‡ÂŒĂ€ĂŤĂŞchars§LÂŤĂ­Ă˜Ă‘y3charsÂĽ iĂŽ"ĂŽ ‡ s.strip ƒ us.strip("\t \n\r")" iĂŽG ĂœÂż(join)ĂšŠ)(split) s.join(words)§words´ ˜ ‡ Â? š k i ĂŽ G tuple ½ Ăślist "join^sŠ Â? Š Â… ĂŽ òwordsÂĽ iĂŽGĂŤ ĂĽ5§ĂœÂżÂ?˜‡iĂŽG" >>> "\n".join(["Hello","World","Python","Said"]) ’Hello\nWorld\nPython\nSaid’ >>> print "\n".join(["Hello","World","Python","Said"]) Hello World Python Said s.split(words)§words´Â˜Â‡iĂŽG§LŠÂ…ĂŽ"split ܊Újoinƒ‡"ò^sŠ )¤Â˜Â‡list" >>> "This is a book".split(" ") [’This’, ’is’, ’a’, ’book’]

§1.6 |(tuple) P4Âąe5K§Ă„ ĂžĂ’ÂŒÂąĂ?Âştuple" • • • •

tuple´~Ăžlist"tupleĂ˜Upop§remove§insert Â?{" tuple ^() L§Xa=(0§1§2§3§4)§)Ă’ÂŒÂąÂŽĂ‘" tuple ÂŒÂą^eIÂˆÂŁ ƒ½Üftuple" tuple ÂŒÂą^uþ‡CĂž DŠ" >>> >>> 1 2 >>> >>> >>> 1 2

a,b=(1,2) print a,b t=(1,2) a,b=t print a,b

annCharles@tom.com

122Â?, 208Â?

Python ÆS)P


§1.7 S (sequence) >>> a,b=b,a+1 >>> print a,b >>> 2,2 • LÂŤÂ?šk˜‡ ƒ tuple Â?{´: (1§) Š"

ÂĄk‡Ă?Ă’§^5ÚßÕ CĂžÂƒÂŤ

tuple 'list 5UĂ?§Â?Ă’´`§Ă˜^JøĂ„ S +n ĂľU"

§1.7 S (sequence) sequence Â?)string§list§tuple"Œ‚ÑkÂąe˜ Ă?^ ܊" • in ä,‡object ´Ă˜´3˜‡sequence ÂĽ" >>> x=12 >>> l=[12,13] >>> if x in l : print "x is in l" ... x is in l >>> str="abcd" >>> if "a" in str: print " ok " ... ok >>> if 2 in T : print "OK" ... OK • • • • • •

sequence Ă?len(seq) Ă?LeI Ă™ÂĽÂ˜Â‡ ƒ" seq[i] Ă?L‘kĂ’ eI fsequence§seq[start:end] ^+ LÂŤĂŤ ߇sequence ^* L­E˜‡sequence§"a"*3 LÂŤaaa§(1,2)*3LÂŤ(1,2,1,2,1,2) ÂŒ¹Œ^list comprehension"

§1.8 i;(dictionary) dictionary ´ ˜ ‡ Ăƒ S ; ( " z ˜ ƒ ´ ˜ ‡pair§ Â? )keyĂšvalueĂź ‡ Ăœ Š "key a . ´integer½ Ăśstring1 "value a . ‘ B Â&#x; o Ă‘ ÂŒ Âą "dictionaryÂĽ v k ­ E key"dictionaryÂĽ z ˜ ‡ ƒ ´ ˜ ‡tuple§tupleÂĽ k Ăź ‡ ƒ § Ăš ‡tuple pair§pairÂĽcÂĄ ´key§ ÂĄ value"ÂŒÂą^D[key] Â?ÂŞ value" 1

½Ü?ÛӞšk hash Ăš cmp

annCharles@tom.com

�{ ʖ

123Â?, 208Â?

Python ÆS)P


˜ Python0

§1.8.1 {Ăź~f # MĂŻÂ˜Â‡{Ăź dictionary ÂŚ^ {} s)Ă’)ĂĽ5§ # z‡pair^Ă?Ă’ŠÂ…§pairÂĽ key3c§value3 §kĂ’ŠÂ…" >>> pricelist={"clock":12,"table":100,"xiao":100 } # Ăš^ dictionary ÂĽ ˜‡ ƒ valuež§^ key ‰eI " >>> pricelist["clock"] 12 >>> del pricelist["clock"] >>> pricelist {’table’: 100, ’xiao’: 100} # dict(L) ÂŒÂą E˜‡ dictionary # Ù¼ L ´Â˜Â‡ list§ LÂĽ z˜‡ ƒ´Â˜Â‡tuple§ # tupleÂĽk߇ ƒ§cÂĄ ´key§ ÂĄ value" >>> pricelist=dict([(’clock’,12),("table",100),("xiao",100)]) >>> pricelist {’table’: 100, ’xiao’: 100, ’clock’: 12} >>> pricelist=dict([(x,10*x) for x in [1,2,3]]) >>> pricelist {1: 10, 2: 20, 3: 30} #eĂŠÂ˜Â‡Ă˜ 3 key‰DŠÜŠ§KO\˜‡pair" >>> pricelist["apple"]=12 #O\˜‡ ƒ >>> pricelist {’table’: 100, ’apple’: 12, ’xiao’: 100, ’clock’: 12} #XJĂ–Ă˜ 3 key§ ÑÉ~" >>> pricelist["appled"] Traceback (most recent call last): File "<stdin>", line 1, in ? KeyError: appled

§1.8.2 dictionary ܊ b a={"one":1,"two":2,"three":3,"four":4} ˜˜dictionary ِϴD.clear() >>> a.clear() >>> a {} annCharles@tom.com

124Â?, 208Â?

Python ÆS)P


§1.8 i;(dictionary) ˜˜˜‡dictionary D.copy() ˜‡dictionary ˜‡€ >>> a {’four’: 4, ’three’: 3, ’two’: >>> b=a.copy() >>> b {’four’: 4, ’one’: 1, ’three’: >>> b["four"]=5 >>> b {’four’: 5, ’one’: 1, ’three’: >>> a {’four’: 4, ’three’: 3, ’two’: >>> c=a >>> c["four"]=5 >>> a {’four’: 5, ’three’: 3, ’two’: >>> c {’four’: 5, ’three’: 3, ’two’:

2, ’one’: 1}

3, ’two’: 2}

3, ’two’: 2} 2, ’one’: 1}

2, ’one’: 1} 2, ’one’: 1}

€ "lÞ¥ ~fÂŒÂąw §XJ† DŠc=a§@ocĂša˜ §?Uc SNĂ“ ÂŹ KÂ?a" ´XJb=a.copy()§@ob´Ă•ĂĄ §UbĂ˜ÂŹKÂ?a" D.get(key) eDÂĽkkey§@oÂˆÂŁD[key]§Ă„KÂˆÂŁNone >>> a {’four’: 4, ’three’: 3, ’two’: 2, ’one’: 1} >>> print a.get("abc") None >>> print a.get("four") 4 >>> print a.get("abc",100) 100 D.get(key,default) ĂšD.get(key) Ă˜Ă“3u§eĂƒkey§KÂˆÂŁdefault§ Ă˜´None "D.get(key)ƒ uD.get(key,None)" annCharles@tom.com

125Â?, 208Â?

Python ÆS)P


˜ Python0 D.haskey(key) ^u äD ¼´Ă„škkey§Âƒ ukey in D.keys()" >>> a {’four’: 4, ’three’: 3, ’two’: 2, ’one’: 1} >>> print a.has_key("one") 1 >>> print a.has_key("abc") 0 D.items() ˜‡list§Ă™ÂĽ z‡ ƒ´Â˜Â‡šk߇ ƒ tuple(pair)§tupleÂĽc¥´key§ ¥´value >>> a {’four’: 4, ’three’: 3, ’two’: 2, ’one’: 1} >>> a.items() [(’four’, 4), (’three’, 3), (’two’, 2), (’one’, 1)] D.copy()ƒ udict(D.items()) § ´e– B §^copy()Â?ÂŻ" D.keys() list§škDÂĽ ¤kkey" >>> a {’four’: 4, ’three’: 3, ’two’: 2, ’one’: 1} >>> a.keys() [’four’, ’three’, ’two’, ’one’] a.copy()Â„ÂŒÂą ¤dict([(k,a[k]) for k in a.keys() ]) >>> dict([ (k,a[k]) for k in a.keys()]) {’four’: 4, ’one’: 1, ’three’: 3, ’two’: 2} ,§XJ==´Â? copy§Ă˜Â‡ĂšoZ§^a.copy()§Ă?Â?Â?ÂŻ" D.values() list§škDÂĽ ¤kvalue" >>> a {’four’: 4, ’three’: 3, ’two’: 2, ’one’: 1} >>> a.values() [4, 3, 2, 1] annCharles@tom.com

126Â?, 208Â?

Python ÆS)P


§1.9 §S6§ D.update(E) lEÂĽ # êâ"Âżg´ for k in E.keys(): D[k]=E[k] ~XÂľ >>> a {’four’: 4, ’three’: 3, ’two’: 2, ’one’: 1} >>> b={"five":5,"three":30} >>> b {’five’: 5, ’three’: 30} >>> b.update(a) >>> b {’four’: 4, ’five’: 5, ’one’: 1, ’three’: 3, ’two’: 2} ڍÂ?{ÂŒÂą^5l˜‡dictionary •,˜‡dictionary DŠ" D.popitem() ˜‡pair§¿Â…Ă­Ă˜ÂŚ"eD´Â˜ § ÑÉ~" >>> print a.popitem() (’four’, 4) >>> print a.popitem() (’three’, 3) >>> print a.popitem() (’two’, 2) >>> print a.popitem() (’one’, 1) >>> print a.popitem() Traceback (most recent call last): File "<stdin>", line 1, in ? KeyError: popitem(): dictionary is empty

§1.9 §S6§ ?§ÂŠĂł §S6§kn§^S§Š|§ĂŒÂ‚"

§1.9.1 Š|( if Š{ annCharles@tom.com

127Â?, 208Â?

Python ÆS)P


˜ Python0 if <expr1>: <one_line_statement> ½Ü if <expr1>: <statement-block> ½Ü if <expr1: <statement-block> else: <statement-block> ½Ü if <expr1>: <statement-block> elif <expr2>: <statement-block> elif <expr3>: <statement-block> ... else: <statement-block> ĂšpAT5¿¹eA: • if ÂĄ LÂˆÂŞÂŒ¹´?Ă›Lˆª§Ă˜ None§0§""(˜iĂŽG)§[] (˜list)§{}( ˜dictionary ) ()(˜tuple )Âą §Ă™ÂŚĂ‘´ý" • LÂˆÂŞÂąkĂ’ŠÂ…" • e´Â˜1 {ĂźLˆª§ÂŒÂąÂ† ‹3 ÂĄ" • e´þ1 Lˆª§Ă’‡^ ? Â?ª§LÂŤÂ˜|ŠÊ"3PythonÂĽvkPascal ÂĽ begin ... end §½ÜC Šó¼ { } 5LÂŤÂ˜|ŠÊ mŠĂš(ĂĽ"Python@Â? Ă“  ? Ă? Šʴ˜|"ڴ˜‡;܄; ÂŻÂœ"Ă??Ă’´§Jp ÂŒĂ–5§ ?Ă›<? §SĂ‘´aq §Ă˜Â”CÂĽkÂˆÂŤÂˆ º‚§k r“{â€? ; 3if ¥§k K,ĂĽÂ˜1"Ă˜Ă? /Â?Ă’´§Ú´Â‡#:f§Êþ<Ă‘Ă˜S.§<‚˜ •@Â??§ÂŠó¼Â˜xiĂŽĂ˜AT´ÂŠ{ Â˜ĂœŠ" Â…k ?6ĂŹĂ˜UŠOtab Ăš4£½8¤Â‡Â˜Â‚ ÂŤO§Ă’ÂŹk˜ #œÙŠ Š{Â†Ă˜" • PythonÂĽĂ?”vkswitchŠʧelif^5 ¤Ú‡þU2 " • else‹LÂŤ^Â‡Ă˜ávžAT‰1 ŠʧO# ÂĄ kĂ’" >>> if x>0: 2

‡<@�XJkswitch ŠÊ��

annCharles@tom.com

128Â?, 208Â?

Python ÆS)P


§1.9 §S6§ ... print "x ... elif x==0: ... print "x ... elif x < 0: ... print "x ... else: ... print "x ...

is positive" is zero" is negative" is not a number"

§1.9.2 Ì ( for§while§break§continue§range() forÌ { for x in <sequence>: <statement-block> else: <else-block> • sequenceL«?Ûstring§tuple§dictionary >>> for x in "abc" : print x ... a b c >>> for x in [1,2,3]: print x ... 1 2 3 >>> D={"one":1,"two":2,"three":3} >>> for x in D: print "D[",x,"]=",D[x] ... D[ three ]= 3 D[ two ]= 2 D[ one ]= 1

• break é ±r1òÑÌ §ÚC " annCharles@tom.com

129 , 208

Python ÆS)P


˜ Python0 • else´ÂŒkÂŒĂƒ "ek§KLÂŤXJz‡aÂĽ ÂƒĂ‘ĂŒÂ‚ (vkbreak)§@o ҉1else-block"ĂšÂ˜:ĂŠĂ?§Ă?Â?¡3CŠ󼧲~‡ÚoŠ" for(i=0;i<len;i++){ if(a[i]==100) break; } if(i==len){/*100 not found*/ /*do something*/ } 3PythonÂĽ >>> [1, >>> ... ... ... ... 100

a 2, 3, 4] for x in a: if x==100: break else: print "100 not found" not found

else ÂŠĂŠÂŒÂąn)Â?ÂľXJĂŒÂ‚vk break ŠÊr1¼ä§½Ü`ĂŒÂ‚ ~(ĂĽ §Ă’‰1elseÂĽ ŠÊ"ڄ´)M Š{£ã§ÂŠĂ‚ÂŁĂŁÂŹÂ?\Â˜Ă™§~XĂž ÂĄ ~f§¿g´`XJ3aÂĽĂŠĂ˜ 100§@oҏ‰1elseÂĽ ŠÊ"ŠÂ3ˆ‡ ĂžeŠ ÂœšeÂŹk¤Ă˜Ă“"˜„œše§breakĂ‘ÂŹ3˜‡if ŠÊ ÂĄ3 §elseĂ’ ´L§XJ@‡if ŠÊ3ĂŒÂ‚ÂĽl5Ă‘vk¤åL§Ă’‰1else ÂĽ ŠÊ" Þ¥ ~f¼§if ^‡´x==100§@oXJaÂĽ?Âż ƒx§Ă‘knot x==100§@ oelseÂĽ ŠÊҏ‰1" • ?UxÂżĂ˜U ?Ux3aÂĽĂŠA SN" >>> >>> ... ... >>> 5 >>> [1, 3

a=[1,2,3,4] for x in a: x=x+1 x a 2, 3, 4]

Ă„KĂŒÂ‚Ă’Â” ¿Â

annCharles@tom.com

130Â?, 208Â?

Python ÆS)P


§1.9 §S6§ 5¿§´Ă˜U?Ux3aÂĽĂŠA SN§XJ´Dictionary§@ovk?Ux§ ´Â† ?UDictionary ÂĽ SN"wLname space VgĂş ÚÊg," >>> D={"one":1,"two":2,"three":3} >>> for x in D: ... D[x] += 1; ... >>> D {’three’: 4, ’two’: 3, ’one’: 2} e‡?U§Ă’^range()Ÿê"range([start,]stop,[,step])§LÂŤlstartmŠ§ stop(ü§zĂšO\step§start"ÂŽÂ?0§step"ÂŽÂ?1§ÂˆÂŁÂ˜Â‡list" >>> [0, >>> [1, >>> [1, >>> []

range(10) 1, 2, 3, 4, 5, 6, 7, 8, 9] range(1,10) 2, 3, 4, 5, 6, 7, 8, 9] range(1,10,2) 3, 5, 7, 9] range(1,10,-1)

eÂŒU )Ăƒ Â‡ê§@o´Â˜list§Ă˜ÂŹkkĂŒÂ‚" |^range()Ÿê?Ulist >>> [1, >>> ... ... >>> [3, >>>

a 2, 3, 4] for x in range(len(a)): a[x]=a[x]+2 a 4, 5, 6]

whileĂŒÂ‚ÂŠ{" while <expr1>: <block> else: <else-block> annCharles@tom.com

131Â?, 208Â?

Python ÆS)P


˜ Python0 Ăš ‡ ĂŒ ‚ Âż g ´ § Â? ‡expr1´ Ă˝ § @ o Ă’ ˜ † ‰ 1blockÂĽ Š ĂŠ " X J vbreakaĂ‘ĂŒÂ‚§Â?Ă’´`§3ĂŒÂ‚(ĂĽ žÿexpr1´b§@o‰1else-blockÂĽ ŠÊ" >>> i=0 >>> while i < ... print ... 0 1 2 >>> while i < ... print ... else: ... print ... 0 1 2 i is 3

3: i ; i=i+1

3: i; i = i +1 i , "is 3"

Z O# i=i+1§Ă„KĂ’ÂŹkkĂŒÂ‚"

§1.10 Ÿê Ÿê´Â˜ ĂŁÂŒ¹­EÂŚ^ “è"

§1.10.1 Ă„ Ÿê ^{ Š{: def <function_name> ( <parameters_list> ): <code block> `²: • function_name´Ÿêœ¥§kĂ’^5ŠÂ…Ÿê SN" • parameters_list´Íê L"ĂŤĂŞÂ?vka.§ÂŒÂąD4?Ă›a. Š‰Ÿê§d Ÿê SN½Ă‚Ÿê Â?§XJD4 ĂŤĂŞ a.Ă˜´ŸêŽ‡ §@oŸêÂŒÂą ÑÉ~" • code block´Ăšif§while˜ “è"5ÂżATkÂƒĂ“  ?" annCharles@tom.com

132Â?, 208Â?

Python ÆS)P


§1.10 Ÿê • ŸêvkÂˆÂŁÂŠa.§returnÂŒÂąÂˆÂŁ?Ă›a." ~f: >>> def add(a,b): ... return a+b; ... >>> print add(1,2) 3 >>> print add("abc","def") abcdef >>> print add("abc",12) Traceback (most recent call last): File "<stdin>", line 1, in ? File "<stdin>", line 2, in add TypeError: cannot concatenate ’str’ and ’int’ objects >>> myadd=add >>> myadd(1,2) 3 ِϴÂ?´Â˜Â‡CÞ§Â˜Â‡ĂŠÂ–"P â€œÂ˜ÂƒĂ‘´Ê–â€?"¤¹ÂŒÂąÂ”ĂŠĂ?ĂŠÂ–Â˜ § r˜‡ŸêDŠ‰,˜‡CĂž"myadd=add§Úk:”ŸêÂ? "⊠‰function alias§ ŸêOÂś"

§1.10.2 ĂŤĂŞÂ‡ĂŞÂŒĂ€§Íêk%@Š P C++§VBÂĽ ÂŒCꐤPython˜ kaq ś"~f: >>> def myjoin(str,sep=","): ... return sep.join(str) ... >>> myjoin(["a","b","c"]) ’a,b,c’ >>> myjoin(["a","b","c"],";") ’a;b;c’ sep "ŽŠ´â€œ§â€?§^Ă?Ă’Š §XJvkJøsep ꐤ@o§Ă’^“§â€?" ´XJ˜ ‡Íê´ÂŒĂ€ §@oÂŚ ÂĄ ¤kĂŤĂŞĂ‘AT´ÂŒĂ€ĂŤĂŞ" >>> def myrange(start=0,stop,step=1): ... print stop,start,step ... annCharles@tom.com

133Â?, 208Â?

Python ÆS)P


˜ Python0 SyntaxError: non-default argument follows default argument

§1.10.3 UCŸêÍêDŠ^S XJ½Ă‚ ˜‡¹Þ ÂŒĂ€ꐤ 5´Ă˜UUCĂŤĂŞ D4^S § >>> def printValues(name,height=170,weight=70): ... print("%s’s height is %d cm," ... " his weigth is %d kg\n"%(name,height,weight)) ... >>> printValues("Charles") Charles’s height is 170 cm, his weigth is 70 kg >>> printValues("Charles",175) Charles’s height is 175 cm, his weigth is 70 kg >>> printValues("Charles",175,85) Charles’s height is 175 cm, his weigth is 85 kg >>> ´ÂŒÂąĂ?LeÂĄ Â?ÂŞUCĂŤĂŞ ^S" >>> printValues("Charles",weight=85) Charles’s height is 170 cm, his weigth is 85 kg

§1.10.4 Â‡ĂŞÂŒCĂŤĂŞ XJ^LCŠó¼ printf()§@oĂ’ÂŹĂŠĂŤĂŞÂ‡ĂŞÂŒC ¿Â' )"ÂŚ+ÂŒĂ€ĂŤ ĂŞ ś-Ÿê Íê‡ê´ÂŒC § ´Â„´k Â›§Íê‡êk ÂŒ Â›§ …„‡Â? ²= ´ÂŒĂ€ĂŤĂŞ" e¥Ú‡Å›§ÂŒÂą É?¿þ‡Íê" >>> def printf(format,*arg): ... print format%arg ... >>> printf ("%d is greater than %d",1,2) 1 is greater than 2 Ù¼*arg7L´ Â˜Â‡ꐤ*LÂŤ É?¿þ‡ꐤĂ˜ cÂĄ ĂŤĂŞ ÍêъÂ?˜‡tupleD4‡Ÿêprintf§ÂŒÂąĂ?Larg5–¯"

§þ{

>> def printf(format,*arg): ... print type(arg) ... print format%arg >>> printf("a",1) <type ’tuple’> annCharles@tom.com

134Â?, 208Â?

Python ÆS)P


§1.10 Ÿê 3Ÿê¼§arg ´Â˜Â‡tuple§ÂŒÂąĂ?L–¯tuple Â?{§5–¯arg" „kÂ˜ÂŤÂ?ÂŞ5¢y?¿‡êÍê§Ă’´ÍêUĂŹdictionary Â?ÂŞD4‡Ÿê§Ÿê Ă“ ÂŒÂą É?¿þ‡Íê" >>> def printf(format,**keyword): ... for k in keyword.keys(): ... print "keyword[%s] is %s"%(k,keyword[k]) ... >>> printf("ok",One=1,Two=2,Three=3) keyword[Three] is 3 keyword[Two] is 2 keyword[One] is 1 Ă“ĂžÂ˜ÂŤĂ…Â›aq§Â?Ă˜L**keyword´^**LÂŤ É?¿‡ê kÂśi ĂŤĂŞD4§ ´ N^Ÿêž§Â‡Â?²Íê Âśi§One=1,Two=2,Three=3§3Ÿê¼§ÂŒÂą^dictionary Â?ÂŞ5܊keyword§Ă™ÂĽkeys´["One","Two","Three"]§values´[1,2,3]"„Œòߍ śÚ3Â˜ĂĽ"ڞ§*arg§Â‡Â˜3**keywordcÂĄ" >>> printf("%d is greater than %d",2,1,Apple="red",One="1") 2 is greater than 1 keyword[Apple]=red keyword[One]=1 Â„ÂŒÂąrÚߍĂ…Â›ĂšÂŒĂ€ĂŤĂŞĂ…Â›Ăœ3Â˜ĂĽÂŚ^" >>> def testfun(fixed,optional=1,*arg,**keywords): ... print "fixed parameters is ",fixed ... print "optional parameter is ",optional ... print "Arbitrary parameter is ", arg ... print "keywords parameter is ",keywords ... >>> testfun(1,2,"a","b","c",one=1,two=2,three=3) fixed parameters is 1 optional parameter is 2 Arbitrary parameter is (’a’, ’b’, ’c’) keywords parameter is {’three’: 3, ’two’: 2, ’one’: 1} Ÿê ÉÍê ^S§k É ½Íê§, i ?¿Íê" annCharles@tom.com

´ÂŒĂ€ꐤ,

135Â?, 208Â?

É?¿Íê§Â

´Â‘Âś

Python ÆS)P


˜ Python0

§1.10.5 Doc String Ÿê£ã òŠ 3§Sp§´LISPÂĽ ˜‡AĂš§PythonÂ?/ L5"z‡ŸêĂ‘´Â˜ ‡Ê–§z‡ŸêÊ–Ñk˜‡__doc__ ĂĄ5§ŸêŠʼ§XJ1˜‡Lˆª´Â˜ ‡string§Ú‡Ÿê __doc__Ă’´Ú‡string§Ă„K__doc__´None" >>> def testfun(): ... """ ... this function do nothing, just demostrate the use of the ... doc string. ... """ ... pass ... >>> print testfun.__doc__ this function do nothing, just demostrate the use of the doc string. >>> passŠʴ˜ŠʧÂ&#x;oÂ?Ă˜Z§Ă’”CŠó¼ {}"Ă?LwÂŤ__doc__§Â‚ÂŒÂą w˜

SĂœŸê Â?Ă?&E" >>> print " ".join.__doc__ S.join(sequence) -> string Return a string which is the concatenation of the strings in the sequence. The separator between elements is S. >>> print range.__doc__ range([start,] stop[, step]) -> list of integers Return a list containing an arithmetic progression of integers. range(i, j) returns [i, i+1, i+2, ..., j-1]; start (!) defaults to 0.When step is given, it specifies the increment (or decrement). For example, range(4) returns [0, 1, 2, 3]. The end point is omitted! These are exactly the valid indices for a list of 4 elements. ^ڍÂ?{§ wÂ?Ă?§´Â›Šk "Š Ăš§S3˜ü§kĂ?u ¹Š Ăš§S ˜— 5"

§1.10.6 lambdaŸê Ă™ Gfunctional programming < § Ă˜ ÂŹ ĂŠlambdaÂź ĂŞ a ) ) "LISP´ ˜ ÂŤfunctional programming language" Ă˜ Ă™ Gfunctional programming < § ÂŒ Âą @ annCharles@tom.com

136Â?, 208Â?

Python ÆS)P


§1.10 Ÿê Â?lambdaŸêĂ’´Â˜ÂŤ{Ăź ]œŸê" >>> f = lambda a,b: a+b >>> f(1,2) 3 >>> f("abc","def") ’abcdef’ f dudef f(a,b): return a+b" ˜‡ŸêÂŒÂąÂˆÂŁÂ˜Â‡lambdaŸê"X >>> ... ... >>> 14 >>> 15 >>> 17 >>>

def incfun(a): return lambda x: x+a incfun(2)(12) incfun(2)(13) incfun(4)(13)

§1.10.7 Ÿê Š^Â?(scope) ĂšpP4˜‡LGB 5K§python ˜‡CĂž ÂśikĂŠlocal name space (Ă›Ăœ¡ ÂśÂ˜m)§3ĂŠglobal name space( Ă›¡œÂ˜m)§, ´buildin name space (S3¡œÂ˜ m) ^globalÂŠĂŠÂŒÂąUC, CĂž ¡œÂ˜m" >>> >>> ... ... ... >>> 2 >>> 1

a=1 def testfun(): a=2 print a testfun() a

3Ÿêtestfun()ÂĽa´3local name space ¼§?UaĂ˜ÂŹUCglobal name space ÂĽ a ´§^globalÂŠĂŠÂŒÂą?U˜‡CĂž ¤3 name space" >>> a=1 annCharles@tom.com

137Â?, 208Â?

Python ÆS)P


˜ Python0 >>> def testfun(): ... global a ... a=2 ... print a ... >>> testfun <function testfun at 0x8176264> >>> testfun() 2 >>> a 2 >>>

§1.10.8 i@Ÿê(nested) Python¼Ÿê´ÂŒÂąi@ " >>> def outfun(a,b): ... def innerfun(x,y): ... return x+y ... return innerfun(a,b) ... >>> outfun(1,2) 3 Ăš3CŠó¼´Ă˜#N §Ă?Â?CÂĽ static ŸêÂŒÂąÂ“OڍþU"ڍśJø ˜‡ Ÿê‰Œ Vg§, ŸêÂ?3, Ÿê SĂœ§âw §XJŒ‡úm {§ÂŒÂąĂ?L ÂˆÂŁÂŠ§ÂˆÂŁSĂœŸê"5¿§ĂšPascal Ă˜Â˜ §i@ŸêĂ˜U–¯ Ÿê CĂž"¡ @Â?i@Ÿê ^?Ă˜ÂŒ"

§1.10.9 function ĂŤĂŞD4 python´UŠD4 ĂŤĂŞ § ´Â„´kÂŒUUCÍê¤Â? Š" >>> ... ... ... >>> >>> >>>

def change(x,y): x=2 y[0]="hello" x=1 y=[1,2] change(x,y)

annCharles@tom.com

138Â?, 208Â?

Python ÆS)P


§1.11 ÂŹ(module)ĂšÂ?(package) >>> x 1 >>> y [’hello’, 2] ÂŒÂąw §x ŠvkUC§ ´y Š%UC "30 name space Vg ÂŹĂş Ăš ´3g,Ă˜L ÂŻÂœ "ĂŤĂŞx§y Ă˜L´3function local name space ÂĽMĂŻ ˜‡# name §Ăšfunction N^ĂśD?5 ĂŤĂŞÂ?Â•Ă“Â˜Â‡ĂŠÂ–"3function SĂœx=2§Â?´U C name x bind 'X§4ڇname Â?•˜‡# ʖ"¤¹Ă˜ÂŹKÂ?N^ĂśD?5 Íê¤Â? ʖ" y[0]="hello" ÂżvkUCy bind 'X§ ´Â† ?Uy¤Â?• ĂŠ –§@o ,Ă’ÂŹUCN^ĂśD?5 ĂŤĂŞ "w ÂĄname space VgÊڇkÂ? n)"

§1.11 ÂŹ(module)ĂšÂ?(package) §1.11.1 MĂŻÂ˜Â‡module ˜‡module Ă˜L´Â˜ Ÿê§class˜3˜‡ŠÂ‡ÂĽ"~X§3 c8š(current directory)MĂŻÂ˜Â‡ŠÂ‡ testmodule.py§SN´ """ this only is a very simple test module """ age=0 # a sample attribute def sayHello(): # a sample function in a module print "Hello" if __name__ == "__main__" sayHello() ˜‡module Â?kaqfunction doc string"Ă˜ 5Âş 1˜^ŠÊXJ´Â˜Â‡iĂŽ G {§@oڇiĂŽGĂ’´doc string§ÂŒÂą w˜‡doc string5 Â?Ă?"import ˜ ‡module kߍÂ?{" >>> import testmodule >>> print testmodule.__doc__ this only is a very simple test module >>> ÂŒÂąÂ–ÂŻtestmoduleÂĽ attribute annCharles@tom.com

139Â?, 208Â?

Python ÆS)P


˜ Python0 >>> testmodule.age 0 >>> testmodule.age=1 >>> testmodule.age 1 >>> testmodule.sayHello <function sayHello at 0x8174a34> >>> testmodule.sayHello() Hello >>> sayHello=testmodule.sayHello >>> sayHello() Hello >>> sayHello <function sayHello at 0x8174a34> >>> >>> othermodule=testmodule >>> othermodule.age=100 >>> testmodule.age 100 ÂŒ Âą w § Ă? Lmodname.attribute Â? ÂŞ ÂŒ Âą – ÂŻ §module ÂĽ attribute § 3module ¼½Ă‚ CÞ§Ÿê§class Ă‘´module attribute "^name space Vg 5)ºÒÂ?BĂľ §module ÂĽ name space ÂĽ Â˜ÂƒĂ‘´module ˜‡attribute§Â‡L5 `module attribute ´module name space ÂĽ ˜‡name" sayHello=testmodule.sayHello()§ ÂŒ Âą 3global name space ÂĽ ĂŻ ĂĄ ˜ ‡name§map(N ) testmodule name space ÂĽ ˜ ‡name ¤ Â? object" ÂŒ Âą w Ăź ‡sayHello Â? • Ă“ ˜ ‡function object" ÂŚ + ÂŚ ‚ Ă‘ ´sayHello§ ÂŚ ‚ Â? Â? • Ă“ ˜ ‡ ĂŠ – § ´ ÂŚ ‚ 3 Ăź ‡ Ă˜ Ă“ name space ÂĽ "module Â? ´ ˜ ‡object§testmoduleĂ’ ´ ÂŚ name§ ÂŒ Âą 3global name space ÂĽ ĂŻ ĂĄ , ˜ ‡name ĂštestmoduleÂ?Â•Ă“Â˜Â‡object§Â˜Â‡module object"othermodule = testmodule"XJ ˜‡moduleÂĽkĂŠĂľk^ functions§ ´Ă?Lmodulename.funcname Â?ª§Ă’w ĂŠ ̆"ÂŒÂą^1 ÂŤimport module Â?{"­#?\python§, " >>> from testmodule import age, sayHello >>> age 0 >>> sayHello <function sayHello at 0x81631a4> annCharles@tom.com

140Â?, 208Â?

Python ÆS)P


§1.11 ÂŹ(module)ĂšÂ?(package) >>> sayHello() Hello >>> testmodule Traceback (most recent call last): File "<stdin>", line 1, in ? NameError: name ’testmodule’ is not defined >>> ÂŒÂąw §ÚÂ?{ƒ u import testmodule age=testmodule.age sayHello=testmodule.sayHello ´ k Ă˜ Ă“ § ^from Â? { §testmodule Ăš ‡ Âś i § Âż v k import ? 5 § Â? Ă’ ´ ` § cname space ÂĽ v ktestmodule Ăš ˜ ‡name§ import testmodule Ă’ ÂŒ Âą 3 cname space ÂĽ M ĂŻ ˜ ‡testmodule Ăš ˜ ‡ name" ÂŒ Âą ^ from testmodule import * òtestmodule ÂĽname space ÂĽ ¤ kname Ăš ? c name space ¼§Ă?LĂš name§Â–ÂŻname¤Â? ʖ" Â…import testmodule § X Jtestmodule.py? U L § ÂŒ Âą ^reload(testmodule)­#\1testmodule"

§1.11.2 No ĂŠmodule python^ÂąeĂš½ ĂŠÂ˜Â‡module§¹import testmoduleÂ?~f" • 3 c8š¼ ĂŠtestmodule.py" • evĂŠ §3‚¸CĂž(environment variables) PYTHONPATHÂĽ ʧҖ3PATHÂĽ ĂŠÂŒÂ‰1ŠÂ‡Â˜ " • e ĂƒPYTHONPATHC Ăž § @ o 3 S C 8 š ÂĽ ĂŠ § 3unix ÂĽ ´.:/usr/local/lib/python Ă™¢§python´3sys.pathÂĽ ¤k8š¼ ĂŠmodule "ÂŒÂą wsys.path" >>> import sys >>> print sys.path [’’, ’/usr/lib/python2.2’, ’/usr/lib/python2.2/plat-linux2’, ’/usr/lib/python2.2/lib-dynload’, ’/usr/lib/python2.2/site-packages’] l ĂŠ^SĂžw§¡Â‚ÂŒÂą XJ\3 c8šïå Â˜Â‡ĂšIO¼¼‘k I OmodulekÂƒĂ“ Âśi@oÂŹ^\ module “OXĂšmodule§ )#œÙŠ ÂŻK§¤ ¹¡Â‚‡5¿§gC module ÂśiĂ˜Â‡ĂšXĂš moduleÂśiÂƒĂ“" annCharles@tom.com

141Â?, 208Â?

Python ÆS)P


˜ Python0

§1.11.3 package(Â?) package ´Â˜|module 8Ăœ"^ÂąeÂ?{MĂŻÂ˜Â‡package" • y3 c8šMĂŻÂ˜Â‡8štestpackage • 3testpackage MĂŻÂ˜Â‡Â˜ŠÂ‡__init__.py • 3testpackage ÂĽMĂŻÂ˜Â‡testmodule"py§p¥šk˜ “è"ĂšpÂ? {ߧĂ’ Ăštestmodule.py˜ " ĂĽĂ„python >>> import testpackage.testmodule >>> testpackage.testmodule.sayHello() Hello package ´ ˜ ÂŤ | „module Â? { § J ø ˜ ‡name space§ “ ÂŽ u ) Âś i Ă€ â"package ÂĽÂ„ÂŒÂąkpackage§¤¹ÚÂ?ÂŞÂŒ¹ÊĂ? |„˜‡äG( §^5+ nmodules"

§1.12 name space(¡œÂ˜m) 3cÂĄ 0 ¼§Ă˜ÂŽÂ˜g J name space§y0 name space Vg§Ú´Â˜Â‡ p?Vg§ ´XJn)Œ§ÊþĂ€ĂœĂ‘ĂŠN´n)"ӞÂ?ÂŹaĂş python ´Â˜ÂŤ/ÂŞ {ߧVg˜Ă&#x;§VgĂšÂ˜ Šó" Â&#x;o´name space? name space ´lϴ(name) ʖ(object)Ăž N (map)" ˜ ‡name N ˜‡object ޞ§¡Â‚`ڇname ÚڇobjectkÂ?½(bind)'X§½Ü` ڇname Â?•Ú‡object" ­E `§python ÂĽÂ˜ÂƒĂ‘´object §Â?)function §module §class §package "Ăš objectsĂ‘k3S ¼ýý 3§Ă’”)š3­Þ z˜‡<" ´¡Â‚ NoĂŠ Ăš objectsQ? ^name! ‰z‡object ü‡œi"z‡name Â?ĂŠA˜‡object ˜‡objectÂŒÂąkþ‡œi" ´name Ă˜´object §Ă’–˜‡<Âśi Charles§ ´Charles Ă˜´Ú‡<§´Ú‡< Âśi§Ú‡<´kÉkSÂŹ ĂĄ §Charles Ă˜ §Charles´ÂŒÂą 3Â’Ăž "˜‡<Â?ÂŒÂąkþ‡œi" PythonÂĽ k ĂŠ Ăľ name space§ ~ ^ k: build-in name space (S 3 ¡œ ˜ m) global name space ( Ă›¡œÂ˜m)§local name space(Ă›Ăœ¡œÂ˜m)"3Ă˜Ă“name space ÂĽ name ´Â˜:'XÂ?vk "$–iÂĄĂžÂƒĂ“name§Â?‡Œ‚3Ă˜Ă“ name space ¼§@oÂŚÂ‚Ă’ĂŽĂƒ'ĂŠ"UClocal name space ÂĽ name bind 'X§Ă˜ÂŹKÂ? global name space ÂĽÂƒĂ“ name" z‡object Ă‘kgC name space"ÂŒÂąĂ?Lobject.name Â?ª–¯object name space ÂĽ name"z‡object name space ´Ă•ĂĄ "â€œĂ•ĂĄ â€? Âżg´`§Â˜Â‡object annCharles@tom.com

142Â?, 208Â?

Python ÆS)P


§1.12 name space(¡œÂ˜m) name space ÂĽ ˜‡name§ĂšĂ™§name space ÂĽ name ´Â˜:'XÂ?vk §$– ߇iÂĄĂžwĂĽ5˜ name§Â?´ĂŽĂ˜ÂƒZ "Ă’Â”â€œÂ?fâ€? ڇobject§3ÂŚ name space ÂĽkÂ˜Â‡â€œĂ´Ăšâ€?§Ú ˜‡name §LÂŤÂ˜Â‡Â?f Ă´Ăš§ “’fâ€?ڇobject §3 ÂŚ name space ÂĽÂ?kÂ˜Â‡â€œĂ´Ăšâ€?§Ú‡name LÂŤÂ’f Ă´Ăš§ŒĂšÂ?f˜:'XÂ?v k§Œ+Œ‚Ñ â€œĂ´Ăšâ€?" ¡@Â?ÂŚ+name space ´Â˜Â‡p?Vg§ ´Œ´Ê˜Ă&#x; Vg§Â˜Â‡N´n) V g"{Ăź Vg ¥ÛþXÂŒ ÂŻ"name space ´Ú‡)PÂĽ`  þ§ Ă› ˜‡V g"¡@Â?§Œ´python Ă˜%Vg§Ă’”file ڇVgunix ÂĽÂ˜ " z ˜ ‡object § Xmodule§class§function§ ˜ ‡instance § Ă‘ k g C name space"name space ´Ă„ MĂŻ "z˜‡name space ) žmÂ?Ă˜Â˜ " ˜‡module name space ´Ú‡module import žÿMĂŻ " k˜‡AĂ? module §Â˜?\python )ºÏ§Ă’ĂŻĂĄ ˜‡ module§Ú‡module name space Ă’´global name space§Â˜Â‡ Ă›Â?˜ name space"ڇmodule ˜‡S Ăœ attribute§__name__ ^5IÂŁmodule§Ú‡module __name__ ´__main__" >>> print __name__ __main__ z˜‡module Ă‘k˜‡__name__ attribute§^5LÂŤ cmodule Âśi"¤¹z ˜‡module Ă‘kĂš “è" if __name__ == "__main__" sayHello() # ÿà “è ^ umodoule Ăż Ă " Ă? Â? 3 ˜ ‡module 3 import ž Ăż § ÂŚ name space ÂĽ M ĂŻ

˜ ‡ S ˜ name§__name__§ ^ 5 L ÂŤmodule Š ‡ Âś ÂĄ " ¤ Âą 3 import ž Ăż § Ăż à “ è Ă’ – Ă˜ 3 ˜ § Ă? Â?__name__§ [ Ă˜ ÂŹ ´â€œ__main__â€?" ´ X J ^python testmodule.py Â? ÂŞ † $ 1 ˜ ‡module ž Ăż § Ă˜ ´import§ @ omodule name space Ă’ ´global name space , Ăš žpython g Ă„ rglobal name space ÂĽ __name__ Â?“__main__â€?§@oĂ’ÂŒÂą$1ÿà “è " ˜‡N^˜‡function žÿ§function local name space MĂŻ § functionˆ ÂŁ žÿ§½Üfunction Ă‘exception žÿ§local name space Ă­Ă˜ " >>> def testfun(): ... print locals() ... print globals() ... >>> >>> testfun() annCharles@tom.com

143Â?, 208Â?

Python ÆS)P


˜ Python0 {} {’__builtins__’: <module ’__builtin__’ (built-in)>, ’__name__’: ’__main__’, ’testfun’: <function testfun at 0x8174dd4>, ’__doc__’: None} >>> locals()Ăšglobals()Š O ˆ ÂŁglobal name space Ăšlocal name space"name space Ă? ~ ^dictionary 5 L ÂŤ §dictionary ´ ˜ ‡(key§name)Ăš pair 8 Ăœ §key ´name§value´name ¤Â? object" Â&#x;o´scope(Š^Â?)? scope Ă’´python ÂĽ “èli¥¿Â(textually)ĂžÂŒÂąâ€œÂ† –¯â€? name 8Ăœ"Ăšp)ºß‡Vg: • Ҡ –¯â€? Âżg´^unqualified reference name Ă’ÂŒÂąÂ† ĂŠ name ¤Â? ʖ" • unqualified reference Ă’´Ă˜šk. name"a Ă’´Â˜Â‡unqualified name§a.b Ă’Ă˜ ´" LGB 5 K ^scope V g 5 ) Âş Ă’ ´: 3 ? Ă› “ è ‰ 1 ž Ăż § Ă‘ – k n ‡scope§Â˜Â‡´local name space |¤ scope"˜‡´ cmodule global name space |¤ scope§Â„kbuildin name space |¤ scope"lS Â?g ĂŠÂ˜Â‡unqualified name"L Â?local§G Â?gloabl§B Â?buildin" globalÂŠĂŠÂŒÂąUCr˜‡unqualified name scope§Â† global name space ÂĽ ĂŠ" function alias Âżg´Â?alias=module_name.funcname Â?ÂŞMĂŻ ˜‡function OÂś" >>> def sayHello(): ... print "Hello" ... >>> saidHello=sayHello >>> saidHello <function sayHello at 0x8174bb4> >>> sayHello <function sayHello at 0x8174bb4> >>> sayHello() Hello >>> saidHello() Hello ÂŒÂąw sayHello§saidHelloÂŚÂ‚Ă˜L´ß‡œi§ŒÂ‚Â? ´Ă“ object"Ă’Â–Â˜ ‡ < k Ăź ‡ Âś i ˜ "a=[1,2]Ăš Š ĂŠ § ÂŹ 3  S Ăœ name space Ăž M ĂŻ ˜ ‡name annCharles@tom.com

144Â?, 208Â?

Python ÆS)P


§1.12 name space(¡œÂ˜m) Ăš[1,2]ڇobject Â?½(bind)"ڍDÂŠÂŠĂŠĂ˜ÂŹÂ€ êâ§Â?´3namespaceÂĽMĂŻ

˜‡# name§Â?•˜‡object"Úʭ‡"Ҕjava ¼¤k CÞÑ´Ăš^(reference)˜ §Â„ĂšC ÂĽpointer(Â? )k aq"3n)˜ §S žÿ§Ú´ÊkÂ?Ă? " ^delÂŠĂŠÂŒÂąlname spaceĂ­Ă˜Â˜Â‡name" >>> a=1 >>> a 1 >>> del a >>> a Traceback (most recent call last): File "<stdin>", line 1, in ? NameError: name ’a’ is not defined Ă­Ă˜Â˜Â‡CĂž Âżg´l SĂœ name space Â˜Ă˜Â˜Â‡name Ăšobject Â?½(bind) 'X§ XJvkٌnameÚڇʖbind§@oâý Ă­Ă˜object"ÚÚjava ÂĽ -ĂƒÂŁĂ‚k

aq"ĂšCĂšC++ÂĽÂœUÂ? EâÊ”" ¢Spython ÂĽĂ’´Œ^ ÂœUÂ? Eâ§z‡name Ă‘ĂšÂ?•object Â? ƒ' ĂŠ § z ˜ ‡objectĂ‘ k ˜ ‡referece counter P 4 k Ăľ ‡name Ăš Ăš ‡object bind" z gbind§reference count Ă‘\1§zgĂ­Ă˜bind 'X§Ă‘~ 1§Â?kreference counter C ¤0 žÿâý Ă­Ă˜ĂŠÂ–" python ´Â˜ÂŤra.§Ă„ a. Šó" r a . ´ Â? § z ˜ ‡ ĂŠ – Ă‘ k ˜ ‡ a . Xtuple §dictionary §list §string §int §long §float §module §function §class §methord Ăš?Ă›^r½Ă‚½Ümodule ½Ă‚ class"Basic Ă’Ă˜´Â˜ÂŤra.§¤¹BasicN´ĂšĂĽĂœĂ‚§~X print "1" + "2" 12 print 1 + "2" 3 Â?N"1"+"2"§\Ă?"´"3" ½Ü"12"§ ´tĂ˜Ăƒ\ .‡Â&#x;o" z‡Ê–ÑkgCĂ•ĂĄ name space"zÂŤa.kgCĂ•ĂĄ ܊Â?{"ʖ name space ÂĽname ÂŹĂš,‡ÜŠÂ?{ÂƒĂŠA"CĂž==´Ê– Âśi" Ă„ a.´Â?z‡CĂžĂ‘Ă˜^(²§ÂŒÂąÂ?•?Ă›a. ʖ"½Ü C Ăž(variable)Â?Âśi(name)Â?Â?Ăœ¡"CĂžÂ?´Â˜Â‡ĂŠÂ– Âśi§z‡CĂž3,˜žÂ?Â? Â•Â˜Â‡ĂŠÂ–§ ´Â˜Â‡ĂŠÂ–ÂŒÂąĂ“Âžkþ‡CĂžÂ?•ΤҔŸê§module §class Ă‘ÂŒÂą kalias (OÂś)"CĂž ) Ă?‡Úʖ ) Ă?´Ă˜Â˜ " vk?Ă›CĂžÂ?Â•Â˜Â‡ĂŠ annCharles@tom.com

145Â?, 208Â?

Python ÆS)P


˜ Python0 – žÿ§Ú‡Ê–â Ă˝ Ă­Ă˜" ˜‡CĂžÂ?ÂŒÂąÂ‘ÂžUCÂŚ Â?½'X§=Â?•ÙŒ ʖ" ڍLˆÂ?ÂŞĂš¡Â‚ y¢­.´Â˜Â—" Â&#x;o´nest function: nest function Â?3function SĂœ½Ă‚ function ʖ"outer funciton ´Â?½Ă‚function function "inter function ´Â? ½Ă‚ function " outer function Ăšinner function vk Â&#x; ÂŤO§´² 'X§outer function local name space 3inner function ¼´Ă˜ÂŒÂ„ " inner function ´outer function SĂœ MĂŻ ˜‡object §Â?•inner function name 3uouter function local name space " outer function ÂŒÂąĂ?LÂˆÂŁÂŠ ś§rinner function ³‰N^Ăś"

§1.13 a ÂĄ • ĂŠ –(OO)´ ˜ ÂŤ ? § g ÂŽ Ă˜ ´ ˜ ÂŤ Š Ăł "Python´ ^CŠ Ăł ´ ¢ y ÂĄ • ĂŠ – Š Ăł "GTKÂ? ´ ^C Â? ÂĄ • ĂŠ – | ‡ ÂĽ "UnixĂś Š X Ăš ÂĽ §â€œÂ˜ ƒ Ă‘ ´ Š ‡â€?§ , ÂŤ Âż Ă‚ Ăž Ăš § ´ ˜ ÂŤ ¤ Ăľ ÂĄ • ĂŠ – § Š ‡ Ă’ ´ ½ Ă‚ ĂŠ Aopen§write§read§close§ioctrl ˜|SĂ˜Ÿê(½Ü Â?{) ʖ" ¥•Ê– 8 ´Â“è­^§~ ­E5 mu"¥•Ê–´Â“è­^śÂ?)Âľ C(encapsulation)§UÂŤ(Inheritance)§þ (Polymorphism)" ¥•Ê– Ă˜%´Ă„–(abstraction)§Šl Â?(interface)Ăš¢y(implemetation)"

§1.13.1 Â&#x;o´object Â˜ÂƒĂ‘´object ! 3Python ¼§object ˜ckÂ?\2Â? šĂ‚§3Ă™§ÂŠó¼§XC++ ¼§object ´Â˜ ‡class instance " ´3Python ¼§object Â?Â?˜ƒ§Â?)§class, module, package, int, float, list, tuple, dict, function, class instance ĂšÂ˜Âƒ^r§S¼½Ă‚ Ă€Ăœ"

)A‡Vg: name space name space ´name Ăšobject ƒm N 'X"z˜‡name Â?˜ ĂšÂ˜ ‡object ”½"˜‡object ÂŒÂąkþ‡name "XJvkname Ăšobject ”½§@ oobject ҏž” "name space ´Â˜Â‡Ă„ êâ( §dictionary " objname = object ÂŹMĂŻÂ˜Â‡name " name name ´Â˜Â‡iĂŽG§Â?•˜‡object "name ´name space ÂĽ ˜‡ ƒ" object object ´Â˜Â‡Ă•ĂĄ name space "object name space ^dictionary LÂŤ"þêÂœ še§obj.__dict__ LÂŤÂ˜Â‡object name space "Ù¼obj.__dict__.keys() L ¤kname list §obj.__dict__[name] LÂŤname ¤Â? object " annCharles@tom.com

146Â?, 208Â?

Python ÆS)P


§1.13 a alias XJ߇name Â?Â•Ă“Â˜Â‡object §@oÚ߇name pÂ?alias " attribute name Š Â? Ăź ÂŤ § ˜ ÂŤ ´unqualified name § ˜ ÂŤ ´qualified name " X Ă“obj.attr /ÂŞ name Ă’´qualified name "XĂ“obj /ÂŞ name Ă’´unqualified name " Attribute Ă’´qualified name ÂĽ “.â€?

ÂĄ ĂœŠ"

• MĂŻattribute Â?{: obj.new_attribute = other ½Ü setattr(obj,"new_attribute",other) • Ă­Ă˜Â˜Â‡attribute Â?{: del obj.old_attribute ½Ü delattr(obj,"new_attribute") • ĂŽÂ˜Â‡attribute Â?{Âľ hasattr(obj,"new_attribute") • ¤kattribute Â?{Âľ dir(obj) kʊ 5Âż ˜:§setattr, getattr, delattr ÂĽ1 ‡Íê´Â˜Â‡string §XJ ÂŽ~fÂĽ^~ĂžN^§Ă’vkÂ&#x;o7‡ §^ĂŠA 1Â˜ÂŤÂ?ÂŞ ÂŒĂ–5ÂŹÂ?Ă?§ ´ŒÂ‚ÂŒÂą ÉÍêCÞ§Â?Ă’´§S3$1 ÂžĂżÂŒÂą?n attribute " ˜ ‡object name space ÂĽ ˜ ‡name ˜ ½ ´object ˜ ‡attribute " ´ ˜ ‡object attribute Ă˜Â˜½3object name space ÂĽ" ˜‡object name space Â?{´vars(obj) § ˜‡object ¤kattribute Â?{´dir(obj) " Ă‘Ăšobject ˜ §Ú VgkÂ?\2Â? šĂ‚§'Ă&#x;3ĂŠĂľPython ŠÂ¼" ~X: Ÿê3ĂŤĂŞD4 žÿ§´UŠD4§Â?O(/`§D4 ´Â˜Â‡alias " def func(a) : return a+1 x=1 func(x) annCharles@tom.com

147Â?, 208Â?

Python ÆS)P


˜ Python0 func /ªÍê´a §N^func(x) žÿ§¢SĂŤĂŞx § ߇name §ŒÂ‚pÂ?alias " UŠD4 Âżg´`UC/ÂŞĂŤĂŞ ÂŠĂ˜ÂŹKÂ?¢SĂŤĂŞ" ´â€œUC/ÂŞĂŤĂŞ Šâ€? ´Â?aqa=2 UC§´Â?4/ÂŞĂŤĂŞÂ?•# ʖ§´Â?UC /ÂŞĂŤĂŞ ”½'X" XJĂŠ/ªÍê܊§Xl.append(1) §@oUC Ă˜´/ªÍê§ ´/ÂŞĂŤ ê¤Â?ʖ " X J Ăź ‡name p Â?alias § @ o ÂŚ ‚ A ˜ ˜ § Ă’ ” Ă“ ˜ ‡ < k Ăź ‡ Âś i"function object alias ˜ Â?ÂŒÂąN^" ´'…‡ŠÂ˜Â&#x;ožÿUC ´name §Â&#x;ožÿUC ´name ¤Â? object " Ă’â€œ=â€? Âżg§Ă˜2´DŠ§ ´Â?4name Â?•# object "4 module object SĂœ½Ă‚ CÞ§Ÿê§aĂ‘´module object name space ÂĽ object " function object ½Ă‚ i@Ÿê§´N^ žÿ§3local name space ÂĽĂ„ MĂŻ ˜ ‡function object "Ăš Â?Ă’n)§Â?Â&#x;oinner function Ă˜U–¯outer function local name space "

§1.13.2 Â&#x;o´class oject ˜‡ {Ăź class object" >>> class SimplestClass: ... pass ... ÂŚÂ&#x;oÂ?vZ§ ´¡Â‚ÂŒÂągĂ? `§¡k ¡ 1˜‡class object" weÂĄ ~fÂľ >>> ... ... ... >>> OK, >>> >>> OK, >>>

class SampleClass: def __init__(self): print "OK, I was born."

4

XJ´D[1]=something §@oLN^D. setitem

a=SampleClass() I was born. AClass = SampleClass b=AClass() I was born.

annCharles@tom.com

Ÿê

148Â?, 208Â?

Python ÆS)P


§1.13 a class SampleClass 'Â…i3 cname space ÂĽ)¤Â˜Â‡name §SampleClass §Â? •˜‡class object " ÂŚ ÂĄ ŠÊÑ´ÂŒÂąÂ‰1 ŠÊ"Ăšdef Ă˜Ă“ ´§3)¤class object žÿ§$ 1ÂŚ ÂĄ ŠʧÚ ÂŠĂŠÂĽ)¤ ˜ƒobject §Ă‘3class object name space ÂĽ"ÂŒÂą ^SampleClass.var1 /ª–¯class object name space ÂĽ object" Ăš ŠÊĂ?~Ă‘´Â˜ {Ăź DŠŠʧĂšdef Šʧ^u3class object name space ÂĽMĂŻobject " ~f¼§AClass = SampleClass Ҕfunction alias ˜ §ïå ˜‡class alias" class object ĂŒÂ‡ÂŠ^Ă’´^5MĂŻclass instance " class object ´ ÂŒ Âą ” Âź ĂŞ ˜ N ^ § N ^ ž Ăż § Ă‘ \ ĂŤ ĂŞ Ă’ ´ Ă? Š z Âź ĂŞ__init__ ĂŤĂŞ"Ù¼ 1Â˜Â‡ĂŤĂŞself Ă˜^Ă‘\§Python ÂŹgĂ„\ÞÚ‡Íê" N^(J´ÂˆÂŁÂ˜Â‡class instance "~X: obj=ClassName()" 3ĂšÂ˜:Þ§class object Ăšfunction object aq§ŒÂ‚Ă‘´callable "ÂŒÂą^Âź ĂŞcallable() 5u Â˜Â‡ĂŠÂ–´Ă˜´ÂŒÂąN^ " XJ˜‡class object ¼­1 AĂ?Ÿê§@oÂŚ)¤ class instance Â?´callable " 3PythonvkC++ÂĽ EŸê5 ÚÛ Ÿê" ´kĂ?ŠzŸê§ ˜‡objectMĂŻ Âą §gĂ„N^__init__ §Ă™8 Ă˜´Â? MĂŻÂ˜Â‡ĂŠÂ–§ ´Â? Ă?ŠzÂ˜Â‡ĂŠÂ– ÂĽ êâ" EŸêĂšĂ?ŠzŸê´kÂŤO § EŸê N^ žÿ§Ê–„vk Mï§Â?Ă’ ´`§ EŸê´3Mïʖ L§¼ N^" ´3Python ¼§Ê–MĂŻÂƒ âN^ Ă?ŠzŸê§Â?Ă’´`§3N^Ă?ŠzŸê žÿ§Ê–Ž²MĂŻ " class object Ăšmodule object kaq /Â?"class object Ăšmodule object ' : ÂƒĂ“ : class object Ăšmodule object ÂĽĂ‘škÂŒÂą$1 ŠÊ"Ăš ŠÊĂ?~Ă‘´Â˜ { Ăź DŠŠʧĂšdef Šʧ^5½Ă‚CÞ§Ÿê " class object Ăšmodule objet Ă‘´Â˜Â‡Ă•ĂĄ name space "Ù¼Â?šÊþ½Ă‚Ă? name Ăšobject "Ăš object Ă?~´function object " module object ÂĽ~~Â?šclass object "class object ÂĽÂ?ÂŒÂąi@½Ă‚class object " class object Ăšmodule object ˜ § 1 ˜ ‡string L ˆ ÂŞ ´doc string " ÂŒ Âą ^__doc__ –¯" Ă˜Ă“ : class object Ăšmodule object  ÂŒ Ă˜Ă“Ă’´§class object ÂŒÂą^ŸêN^ /ÂŞ 5MĂŻÂ˜Â‡# class instance" 5

3new style class ¼k EŸê

annCharles@tom.com

149Â?, 208Â?

Python ÆS)P


˜ Python0 )¤module object Â?{´MĂŻÂ˜Â‡Âąâ€œ.pyâ€? (— ŠÂ‡")¤class object Â?{´ ÂŚ^class 'Â…i" 3 cname space ÂĽMĂŻmodule object Â?{´Œ^import ŠÊ" module 1 ˜gimport ½Ü reload žÿ§$1Ù¼ ŠÊ" 3 cname space ÂĽMĂŻmodule object Â?{´Œ^class ŠÊ" $1Ăš^ŠÊ žÿ§^S$1class object ÂĽ Šʧ3Ă™name space ÂĽMĂŻobject "

§1.13.3 property Ăšmethord ĂšpÂŚ^property Ăšmethord ߇⊧´Ă?Â?Œ‚^ Ăľ "3Python ¼§ 5 vkÚ߇Vg" Ăƒ Ă˜ ´property „ ´methord Ă‘ ´attribute "property ´data attribute §methord ´function attribute " cÂĄ`L§Â˜Â‡object name space ÂĽ ˜‡name ˜½´object ˜‡attribute " ´Â˜Â‡object attribute Ă˜Â˜½3object name space ÂĽ"Ú´Ă?Â?§attribute ´UĂŹ Âąe5K|¢ 1˜‡name " 1. |¢object name space 2. XJobject ´Â˜Â‡class instance §|¢object ¤å class object name space " 3. XJobject ´Â˜Â‡class object § Ă?`k|¢object ¤kyk name space " 4. XJobject k__getattr__ Ÿê§N^ڇŸê§Œ^ÂˆÂŁ(J" UĂŹe –“è£ã ÂŽ{ def search_name(obj,name): #1. |¢ object name space if name in obj.__dict__: return obj.__dict__[name] else: try: # 2. XJ object ´Â˜Â‡ class instance § # |¢ object ¤å class object name space " return search_class(obj.__class__,name) except AttributeError: if obj.has_attr(__getattr__): #4.XJ object k __getattr__ Ÿê§N^ڇŸê§Œ^ÂˆÂŁ(J return obj.__getattr__(name) annCharles@tom.com

150Â?, 208Â?

Python ÆS)P


§1.13 a else: raise AttributeException, "%s not found"%name def search_class(clsobj) # 3.XJ object ´Â˜Â‡ class object § Ă?`k|¢ # object ¤kyk name space " if len(clsobj.__bases) == 0: if clsobj.has_attr(__getattr__): return clsobj.__getattr__(self raise AttributeError, "%s not found"%name for base in clsobj.__bases__: return search_name(base,name) ˜ ‡class object __bases__ § L ÂŤ ÂŚ ¤ k † I a " ˜ ‡class instance __class__ §LÂŤMĂŻÂŚ class object " ~X: class A: # ˜‡{Ăź a a=1 # a ´ A ÂĽ name obj = A() print vars(obj) # # print dir(obj) # # # obj.a=2 # print vars(obj) # print obj.a # del obj.a # print obj.a # A.a = 100 # obj =A() # print obj.a # del obj.a # print obj.b # A.b = 200 # print obj.b #

‹< obj name space, Ă‘Ă‘ {}, Ă?Â? obj name space ´Â˜ ‹< obj ¤k attribute , [’__doc__’, ’__module__’, ’a’] Ă?Â? attribute |¢ÂŽ{ MĂŻÂ˜Â‡ attribute Ă‘Ă‘ {’a’: 2} Ă‘Ă‘ 2,k3 obj name space ÂĽĂŠ a" Ă­Ă˜Â˜Â‡ attribute Ă‘Ă‘ 1,3 A name space ÂĽĂŠ a " UC A ÂĽ a MĂŻ# ʖ Ă‘Ă‘ 100,§3 A name space ÂĽĂŠ a " )É~"Ă?Â? obj ÂĽvk a " )É~"attribute |¢ÂŽ{Ăƒ{ĂŠ b" 3AÂĽMĂŻb Ă‘Ă‘ 200 "attribute |¢ÂŽ{3AÂĽĂŠ b"

annCharles@tom.com

151Â?, 208Â?

Python ÆS)P


˜ Python0 class instance obj Ăšclass object ,A Ă‘kgCĂ•ĂĄ name space §Ă’”¤kobject ˜ §Œ Â‚Ă‘ÂŒÂąĂ•ĂĄ ‘žïå§Â‘ÂžĂ­Ă˜Ă™name space ÂĽ name " class instance obj Ăšclass object ,A 5´ Ă•ĂĄ §vk'X § ´attribute |¢ÂŽ{rŒ‚ÊX3Â˜ĂĽ" attribute |¢ÂŽ{Â?rIaĂšfaĂŠX ˜ü§Ú ¢y UÅ›" z˜‡a ¢~Ă‘k˜‡attribute § ‰__class__ §3%@ Âœše§ ÑÑڇattribute § ΫÂŒÂą^ "

dir Â?Ă˜

Ă˜Ă“ class instance kgCĂ•ĂĄ name space "~X: >>> class B: ... def __init__(self): ... self.a=1 ... >>> obj1=B() # Ă?ŠzŸêÂ?z˜‡ instance MĂŻ a >>> obj2=B() >>> obj1.a # obj1 Ăš obj2 ÂĽĂ‘k 1 # a >>> obj2.a 1 >>> del obj2.a # Ă­Ă˜ obj2 ÂĽ a >>> obj2.a # vk ,Ă˜U3^ obj2.a

Traceback (most recent call last): File "<stdin>", line 1, in ? AttributeError: B instance has no attribute ’a’ >>> obj2.b=1 # MĂŻÂ˜Â‡ obj2.b >>> obj2.b # obj2 k b, vk a 1 # obj1 k a, vk b ÂŚ+Œ‚Ó´ # class B instance

§1.13.4 bound methord Ăšunbound methord 3|¢Â˜Â‡object attribute žÿ§XJattribute ´Â˜Â‡function object §@oĂ’ ‡kAĂ? ?n§rڇfunction object C¤Â?bound methord ½Üunbound methord " bound methord Ăšunbound methord ÂŤO bound methord ĂšÂ˜Â‡class instance ”½" unbound methord Ă˜ĂšÂ˜Â‡class instance ”½" annCharles@tom.com

152Â?, 208Â?

Python ÆS)P


§1.13 a bound methord ÂŹgĂ„rclass instance ŠÂ?1˜‡Íꧤ¹N^ žÿ‡ D4˜ ‡Íê" unbound methord KĂ˜§N^ žÿ§Ă˜U D4Â˜Â‡ĂŤĂŞ" ~X: class A: def h(self): pass a=A() Ă™¼§a.h ´bound methord "A.h ´unbound methord " N^bound methord Â?{´ a.h() § DÂ˜Â‡ĂŤĂŞself §^a “Oself " 51 Â˜Â‡ĂŤĂŞÂŒ¹´?Ă› Âśi§Ă˜Â˜½ÂšÂ‡´self § ´Ú´Â˜Â‡ĂŠĂ? S." N^unbound methord Â?{´A.h(a) §Ă˜U DĂŤĂŞ" ¡Â‚ÂŒþêÂœšŒ^bound methord § ÂœšŒ^unbound methord " ÂŚ^unbound methord ;.ÂœšĂ’´§N^Ia unbound methord " bound methord Ăšunbound methord ÂƒĂ“: Œ‚ 1Â˜Â‡ĂŤĂŞĂ‘´Â˜Â‡class instance §Ú‡class instance Ăšmethord Ă“ĂĄuĂ“Â˜ ‡class object " ÂŚ ‚ Ă‘ ´class object name space ÂĽ function object § ˜ „ Ă˜ ´class instance name space ÂĽ name § Ă˜ š ² w 3class instance name space ÂĽ M ĂŻ ˜ ‡ Ă“ Âś name " bound methord §unbound methord ÚÊĂ?function object ' Ăšp¤` ĂŠĂ?function ´Â?3class ÂŠĂŠÂ›Â›Â‰ÂŒÂƒ ½Ă‚ function object " • ÂƒĂ“: Œ‚Ñ´function object § Â&#x;ĂžÂ˜ "methord ÂƒĂŠuĂŠĂ?function 5`§3? nclass instance Ăšclass object žÿ§¿vkÂ&#x;oĂ˜Â˜ A "=Ϋ bound methord ½Üunbound methord §class object name space ¼§Œ Š^Â?S§Â? Ă˜Â?šclass object ÂĽ name §Â?Ă’´`§ŒĂšĂŠĂ?function ĂŚ^˜ LGB { K§Ă?ĂŠÂ˜Â‡name " Python ÂĽvkٌŠó¼aqthis ½Üme CĂž"z‡methord §Ă‘´class object ˜‡attribute §ŒÂ‚ Ă‚ 1Â˜Â‡ĂŤĂŞĂ’´self "ŒÚÊĂ?Ÿê˜ §Ă‘‡Ă? Lself 5–¯class instance attribute "ŒÚÊĂ?Ÿê˜ §Ă‘ÂŒÂąÂ?class instance Mï§íĂ˜attribute " annCharles@tom.com

153Â?, 208Â?

Python ÆS)P


˜ Python0 • Ă˜Ă“: XJbound methord ½Üunbound methord ¤å class object ´AObj §@omethord 1Â˜Â‡ĂŤĂŞ7L´AObj class instance ½ÜAObj fš class instance "ĂŠĂ? function object vkڇ Â›"

§1.13.5 UÂŤ(inherit) UÂŤ Š{‚ª´ class <name>(superclass1,superclass2,...): ÂŒ Âą k Ăľ ‡ I a " – ÂŻ I a methord  ~ ^ Â? { ´ ÂŚ ^unbound methord§superclass.methord(self,...)" z˜‡ class object Ă‘k˜‡__bases__ attribute §´Â˜Â‡tuple §^uPšŒ ¤k† IŠ" attribute |¢ÂŽ{¢y UÂŤ ś" A Ă˜^”C++ ÂĽ@ AO )ÂşÂ&#x;o´­1§ ƒ"

attribute |¢ÂŽ{Ž²`² ˜

Šâattribute |¢ÂŽ{§kÂąe ­1 JÂľ 1. ˜‡class instance name space ÂĽ name “OÂŚ name §Ă„k |¢ " 2. ˜‡

class object ÂĽ Ă“Âś

class object name “OIaÂĽ Ă“Âśname §Ă„k |¢ "

´3þ­UÂŤ žÿ§Â?Ă’´`§kþ‡Ia žÿ§Â‡5ÂżIa3½Ă‚ÂĽĂ‘y ^ S§Ă?Â?ŒŠâattribute |¢ÂŽ{ݽ Ă’Iaƒm ­1'X" ÂĄÂŹkÂ?\ \ ?Ă˜"

§1.13.6 ¡ ¤ CĂž Â?N\^LC++½ÜJava¼¡ ¤ CÞ§Ă’´Ă“˜‡class Ă˜Ă“instance Â?Ă“Â˜ ‡CĂž"python Â?kڍś§ ´§Ă˜´Ăš? # Ă€Ăœ§Ă?Â?z‡class instance k˜ ‡obj.__class__ attribute Â?•MĂŻclass instance class object "|^ĂšÂ˜:§¡Â‚ÂŒ ¹¢y¡ ¤ CĂž ĂľU" >>> class A: ... count = 0 ... def __init__(self): ... self.__class__.count= self.__class__.count + 1 ... #5ÂżĂ˜´self.count annCharles@tom.com

154Â?, 208Â?

Python ÆS)P


§1.13 a >>> A.count #„vkA instance 0 >>> a=A() # MĂŻÂ˜Â‡A instance >>> a.count # a.count Ăš A.count ´3ĂźÂ‡Ă˜Ă“ name space ÂĽ 1 >>> a.count = 2 # UC a.count >>> a.count 2 >>> A.count # Ă˜ÂŹKÂ? A.count 1 # y3A Â?k˜‡instance >>> a.__class__ # a name space k˜‡ __class__ name <class __main__.A at 0x81566d4> >>> a.__class__ is A # ڇ name Ăš A Ă‘ĂšĂ“Â˜Â‡ class ʖkbind 'X. 1 # Â?Ă’´`,Œ‚´Â˜ÂŁÂŻ,Â? ´Ă“Â˜Â‡Ă€Ăœ >>> b=A() #3MĂŻÂ˜Â‡ instance >>> A.count # __init__ ÂĽ self.__class__ O\ 1 2 # self.__class__ Ăš A Â? ´ĂšÂ˜ Ă€Ăœ. # y3 Ak߇ instance .

§1.13.7

Abstrace Class

Java kinterface §C++ ÂĽabstract class §@opython QÂş class AbstractClass: def AbstrctMethord(self): raise NotImplementedError Ă˜ É~exceptionƒ §vk0 # Vg"ӞÂ?áv abstract class ‡Œ"Ă?Æ¥ •Ê–?§§ú Ú´Ăƒ “è§Â&#x;oÂ?vkZ§Ă†Lƒ §uyÚ´¥Â•ĂŠÂ– Ă˜%g Žƒ˜§Šl Â?Ăš¢y"

§1.13.8 hkattribute XJ3class object ¼½Ă‚ ÂśiáveÂĄ ^‡¾ 1.  ¹ß‡ey‚“__â€? mĂž" 2.  þ¹Â˜Â‡ey‚“__â€? mĂž" Ăš attribute §Ă’´hk " ¢yhkattribute Â?{§âŠ ‰name mangle " annCharles@tom.com

155Â?, 208Â?

Python ÆS)P


˜ Python0 ¯¢Þ§Python ÂĽvkÂ?{¢yĂ˝ hkattribute §Python ¢yÂ?{Ă˜L´U Âśi Ž§Â?‡3½Ă‚class object ÂĽ ŠÊ¼- ávÞ¥^‡ name §Python Ă‘gĂ„ \Ăžâ€œ _classnameâ€? § ~X: >>> class A: ... __prv_a=100 ... >>> vars(A) {’__module__’: ’__main__’, ’_A__prv_a’: 100, ’__doc__’: None} >>> A._A__prv_a=200 >>> vars(A) {’__module__’: ’__main__’, ’_A__prv_a’: 200, ’__doc__’: None} 5Âż__prv_a C¤ _A__prv_a "Ăš ‰ JĂ’´Â“ÂŽ Âż –¯ Ia Ă“ Âśattribute " ´§3§S¼„´kÂŒU–¯hk attribute "Þ¥ ~fÂĽĂ’´Â–ÂŻhkattribute Â?{"ÂŚ^ڍÂ?{3Nà §S žÿ´Êk^ " Ă˜Âš ¿Úo‰§Ă„K–¯hkattribute Ă…´ §ÚĂ…Â›ÂŒÂą3,§Ă? ޓŽ§S Â‹Â†Ă˜"

§1.13.9 Python ¼class A� methord e¥ A�

methord ÂŒÂą ­1§¢yaq

C++ ÂĽ ܊έ1 ĂľU"

3Python ÂĽkĂŠĂľclass AĂ?methord§Â”__init__Ă’´Ă™ÂĽÂ˜Â‡" • __init__ Ž²0 L §Ă’´3obj=A_Class(arg,...)žÿgĂ„N^§§ ĂŤĂŞĂ˜

self „kA_Class ÂĽD4 ĂŤĂŞ" • __del__(self) 3ʖ Ă­Ă˜ žÿ§gĂ„N^"Ă’´`vkname Úڇobject kbind 'X žÿ§N^ÂŚ" • __repr__(self) ÂŚ ^repr(obj) ž Ăż § ÂŹ g Ă„ N ^obj __repr__ Âź ĂŞ § Ăš ‡ Âź ĂŞ ˆ ÂŁ Ăševal() o N ĂŠ – i ĂŽ G L ˆ ÂŞ § ^ u ­ ĂŻ ĂŠ – § Â? Ă’ ´ ` § X Jeval(repr(obj)) ÂŹ Â˜Â‡ĂŠÂ– € " • __str__(self) ‘BÂˆÂŁÂ˜Â‡iĂŽG£ãʖ "eÂĄ ~f`² __repr__ Ăš__str__ Ă˜Ă“" >>> class A: ... def __repr__(self): ... return "A()" annCharles@tom.com

156Â?, 208Â?

Python ÆS)P


§1.13 a ... ... ... >>> >>> ok, >>> A() >>> >>> A() >>>

def __str__(self): return "ok, I am here" x=A() print x I am here print repr(x) b = eval(repr(x)) b

eval(str) ´^5OŽ˜‡python Lˆª§¿Â…ÂˆÂŁĂšÂ‡LÂˆÂŞ"Ú´)ºŠóĂ?^ A5§ÂŒÂą3§SÂĽ §S§ ´rڍ“èÂ€Ăˆ¤C++ ´' (J §Ă?Â?I‡ k)º‰1LÂˆÂŞ ÂŹ"ĂšÂŒĂ˜´Â˜Â‡N´ óŠ" • __cmp__(self,other) ˜‡' ܊Î"0 LÂŤÂƒ §1LÂŤÂŒu§âˆ’1LÂŤ u" >>> ... ... ... ... ... >>> >>> ... >>> ... ok >>> ... ok >>>

class Dog: def __cmp__(self,other): if other > 0 : return 1; elif other < 0 : return -1; else: return 0 dog = Dog() if dog > -10 : print "ok" if dog < -10 : print "ok"

if dog == 0 : print "ok"

Úã“èÂ?´`²__cmp__ ^{§Ă™¢Ú´Ê¡Ă? Â˜ĂŁÂ“è§ ĂšĂŞikÂ&#x;oĂ? ' ? ÂŚÂ?´`² python ŠóA:§Ă’ŽÆ ˜€Šó§Â?˜ ÂŹÂŠĂƒĂ” g" annCharles@tom.com

157Â?, 208Â?

Python ÆS)P


˜ Python0 • __hash__(self)§ÂˆÂŁÂ˜Â‡32 Â? hash value"­1ڇŸêƒ §Ú class instance Ă’ÂŒÂąÂŠÂ? dictionary êâ( ÂĽ key " • __nozero__(self)§¹c¡Â‚5Âż None§"" §() Ă‘LÂŤĂœ6b§Ă™ÂŚĂ‘´ ý§Ă™¢Ă˜ ʧÚpÂŒ¹½Ă‚Â˜Â‡ĂŠÂ–´Ă„´Ăœ6b"XJÂˆÂŁ0 LÂŤĂœ6b§ ÂˆÂŁ1 LÂŤĂœ6Ă˝" >>> class Dog: ... alive=0 ... def __nonzero__(self): ... if self.alive==0 : return 0 ... else: return 1 ... >>> dog = Dog() >>> dog.alive 0 >>> if dog : print "the dog is alive" ... else: print " the dog is dead" ... the dog is dead >>> dog.alive =1 >>> if dog : print "the dog is alive" ... else: print " the dog is dead" ... the dog is alive >>> Úã“èwĂĽ5'ĂžÂ˜Â‡~f„´N´Ăƒ"– ÂŚvk `l " • __len__(self)§3^S˜ŸêlenN^ʖ žÿ§ N^§ÂˆÂŁobject Ă?" XJvk½Ă‚ڇŸê§ N^len(obj)ÂŹ —É~" >>> class EmptyClass: ... pass ... >>> obj=EmptyClass() >>> len(obj) Traceback (most recent call last): File "<stdin>", line 1, in ? AttributeError: EmptyClass instance has no attribute ’__len__’ >>> class Dog : annCharles@tom.com

158Â?, 208Â?

Python ÆS)P


§1.13 a ... def __len__(self): ... return 1000 ... >>> dog = Dog() >>> len(dog) 1000 cÂĄÂ˜ĂœŠ`² vk½Ă‚__len__ ÂŹ —É~§ ÂĄ ~f`² ½Ă‚ __len__ Ă’ÂŒÂą §Â„´Â? `²ÂŠĂł § Â˜ĂŁ ĂŚ Â“è§ NoÂŹk Ă? QÂşlen(dog) ˜‡ Ă?? ĂŽĂƒÂżĂ‚" ´3\ kĂšoÂ˜ÂŤĂ…Â›ÂŒÂą ‰ Ă?§Â?N\3mu˜‡EmailBody class ÂžĂżĂ’ÂŒÂą^len(a_email_body) ÂˆÂŁÂ˜Â‡>fe‡ SN Ă?" ¥„ ˜ ĂƒÂżĂ‚ “è§Â?´Â? `²ÂŠĂł A:" • __getitem__(self,key)§ÂˆÂŁself[key] ^5 [list§dictionary§tuple êâ( " >>> class Zoo: ... def __getitem__(self,key): ... if key == "dog" : return "dog" ... elif key == "pig" : return "pig" ... elif key == "wolf" : return "wolf" ... else : return "unknown" ... >>> zoo=Zoo() >>> zoo["dog"] ’dog’ >>> zoo["pig"] ’pig’ >>> zoo["wolf"] ’wolf’ 5¿§__getitem__ ÂŒ¹ŒÂ˜Â‡ĂŠÂ–”sequence ˜ "3python ÂĽ ⊴§object ¢y __getitem__ protocol ( Æ)§aqjava ÂĽinterface"Â?Ă’´`˜ S˜ Š ʧfor ÂŹÂŚ^Ăš Æ" >>> class A: ... def __getitem__(self,key): ... print "debug: key is %s"%key ... if key >=0 and key <=5: return key * key annCharles@tom.com

159Â?, 208Â?

Python ÆS)P


˜ Python0 ... raise IndexError ... return None ... >>> a=A() >>> for k in a: print k ... debug: key is 0 0 debug: key is 1 1 debug: key is 2 4 debug: key is 3 9 debug: key is 4 16 debug: key is 5 25 debug: key is 6 >>> raise IndexError ´LÂŤ(ĂĽ"return None C vk^ "for ŠÊl0 mŠ§ ^Â˜Â‡Ă˜ä4O key la ÂĽ ʖ"^whileÂŁĂŁÂŚĂ’´ __tmp__ = 0 while(1): try : k = a[__tmp__] ... # for S ŠÊ __tmp__ = __tmp__ +1 except IndexError: break Ú´Â? `² for k in a ŠÂ§ ,^for ŠÊÂ?\{Ăś"\[ Ă˜ÂŹÂŚ^Ăš ÂŤwhileŠÊ“Ofor ŠÊ" • __setitem__(self,key,value)§ [ obj[key]=value" >>> class A: ... def __setitem__(self,key,value): annCharles@tom.com

160Â?, 208Â?

Python ÆS)P


§1.13 a ... print "debug: you want to set [%s] to [%s]"% ... (key,value) ... >>> a=A() >>> a["key"]="value" debug: you want to set [key] to [value] >>> • __delitem__(self,key)§ [ del obj[key] ž§N^TŸê >>> class A: ... def __delitem__(self,key): ... print "debug: you want to del [%s]"%(key,) ... >>> a=A() >>> del a["key"] debug: you want to del [key] __delitem__§__setitem__§__getitem__ Â?´JøÂ˜ÂŤ*Ă?a. Š{§äNŠ Ă‚§ATd\ §Sݽ§ÂŒ¹´Ă?§S§Â?ÂŒÂą Ă‘4<tĂ˜Ăƒ §S" __getslice__(self,i,j)§__setslice__(self,i,j,value)§ __delsclice__(self,i,j) ´ a q " 5 Âż X J v k Â? ½ Ăž  ½ Ăś e  § ÂŚ ^ ˜‡ ÂŒ ĂŞĂš0“O" >>> class A: ... def __getslice__(self,i,j): ... print "you want to get the slice %d:%d"%(i,j) ... def __setslice__(self,i,j,value): ... print "you want to set the slice %d:%d to %s"% ... (i,j,value) ... def __delslice__(self,i,j): ... print "you want to del the slice %d:%d"%(i,j) ... >>> a=A() >>> print a[1:2] you want to get the slice 1:2 None >>> print a[:] you want to get the slice 0:2147483647 annCharles@tom.com

161Â?, 208Â?

Python ÆS)P


˜ Python0 None >>> a[2:3]= [1,2] you want to set the slice 2:3 to [1, 2] >>> del a[:] you want to del the slice 0:2147483647 >>> • __contains__(self,other) ÂŒ¹Œobject ”sequence ˜ §?nin ŠÊ >>> class A: ... def __contains__(self,other): ... if other=="ok" : return 1 ... return 0 ... >>> a=A() >>> if "ok" in a: print "ok in a" ... else : print "ok not in a" ... ok in a • __call__(self,arg1,arg2,...) 4object ”Ÿê˜ §ÂŒÂąN^" >>> class A: ... def __call__(self,*arg):#ĂšpÂŚ^ÂŒCÍêś,‹<¤kD?5 ĂŤ ĂŞ ... for k in arg: ... print k ... >>> a=A() >>> a("hello","World") hello World >>> • ٌŽâ܊ΧXL1.13-4

kÊþŸê¢y ܊έ1 ś§A ¤k python ܊ÎÑkڍ­1ś" \ÂŒÂą ˜‡gC class §4ÂŚwĂĽ5§ ”list §dictionary ˜ §|¹¤k list ¤k ܊ÎڊÊ"3python module lib ¼Ž²kĂš class§ÂŒÂą wŒ‚ annCharles@tom.com

162Â?, 208Â?

Python ÆS)P


§1.13 a �{ __add__(self,other) __sub__(self,other) __mul__(self,other) __div__(self,other) __mod__(self,other) __divmod__(self,other) __pow__(self,other) __pow__(self,other,modulo) __lshift__(self,other) __rshift__(self,other)

(J self + other self - other self * other self / other self % other divmod(self,other) self ** other pow(self,other,modulo) self << other self >> other

L 1.13-4: ÂŒ¹­1 ÂŽâÜŠÎŸê “è§Âš~ å§ ´ÊkdŠ"3lunix ÂĽÂŒÂą3/usr/lib/python2/ ÂĽĂŠ UserList.py UserDict.py"

§1.13.10 ˜ AĂ? ­1Ÿê ^{Ăž~ |^ bases

class

å5‹<a U(

3C++ ¼§class Šʴ˜‡(²ÂŠʧ ´3Python ¼§class ´Â˜Â‡Ă›š DŠ ŠʧŒ)¤ ˜‡aʖ(class object) §5Âż aĂšŸê§ ÂŹ ˜ §Â?´Â˜Â‡ĂŠ –§aʖ(class object)Ăša ¢~(instance) ´ Ă˜Ă“ Ă€Ăœ" z˜‡a ¢~Ă‘kÂ˜Â‡ĂĄ5§ ‰__class__ §Â?Ă’´instance object name space ÂĽ Â˜Â‡Âśi§LÂŤ)¤Ú‡a¢~ aʖ"¤¹ x = obj.__class__() ÂŹ)¤Ăšobj Ă“ a. ¢~" eÂĄ “èÂŒÂąÂ‹<˜‡aʖ(class object) ½Ü¢~ʖ(class instance) UÂŤ( " # browseclass.py import types indent = 0 def printBases(clsobj): # XJ clsobj ´Â˜Â‡ class instance if hasattr(clsobj,"__class__"): return printBases(clsobj.__class__) # XJ clsobj Ă˜´Â˜Â‡ class object annCharles@tom.com

163Â?, 208Â?

Python ÆS)P


Python0 if type(clsobj) != types.ClassType: raise "must input a class objcet as argument" global indent print " "*indent + str(clsobj); indent = indent +2 for b in clsobj.__bases__: printBases(b) indent = indent -2 if __name__ == "__main__": import Tkinter printBases(Tkinter.Button) b = Tkinter.Button() printBases(b) $1(J: $ python browseclass.py Tkinter.Button Tkinter.Widget Tkinter.BaseWidget Tkinter.Misc Tkinter.Pack Tkinter.Place Tkinter.Grid Tkinter.Button Tkinter.Widget Tkinter.BaseWidget Tkinter.Misc Tkinter.Pack Tkinter.Place Tkinter.Grid hasattr ±^5 ä é ´Ä¹k, attribute" ­1 setattr

¢y Öá5

~X: annCharles@tom.com

164 , 208

Python ÆS)P


§1.13 a #readonlyattr.py class A: readonlyValue=100 def __setattr__(self,attr,value): if attr=="readonlyValue": raise "can not change the readonly value" if __name__ == "__main__": a=A() print a.readonlyValue a.readonlyValue = 102

$1(J: python readonlyattr.py 100 Traceback (most recent call last): File "readonlyattr.py", line 12, in ? a.readonlyValue = 102 File "readonlyattr.py", line 7, in __setattr__ raise "can not change the readonly value" can not change the readonly value 3ڇ~f¼§ ĂŠÂ˜Â‡ĂŠÂ– ĂĄ5DŠ žÿ§N^__setattr__ Ÿê§ Ă‚ ÍêŠO´§Ê– (self)§attribute Âśi(attr) §ĂšÂ‡D Š(value)" __setattr__Ÿêu §S‡?U, Â?Ă–ĂĄ5§Ă’ ÑÉ~" ­1 getattr

¢y“na

lattribute |¢ÂŽ{ÂŒÂąw __getattr__ AĂ?Š^" ­1__getattr__ §ÂŒÂąĂ?L|ĂœĂŠÂ– Â?{§Â“OUÅ›" UÅ›ÊN´4a [xĂŒäC ĂŠÂŒ§XJ˜‡ak10 “¹Þ yma§@o‡ ÂŽĂ–Ăƒڍa´Ê(J " ^|ĂœĂŠÂ– Â?ª§ÂŒÂą~ aƒm E,UÂŤ'X§ “ƒ ´Ê–ƒm |Ăœ' X" aUÂŤĂš|ĂœĂŠÂ–´¥Â•ĂŠÂ– ߍ ~^ E^“è Â?ÂŞ"¥•Ê– OÂĽk˜ ‡ K§â€œ`kÂŚ^ʖ|Ăœ§ Ă˜´aUÂŤâ€? " annCharles@tom.com

165Â?, 208Â?

Python ÆS)P


Python0 ~f: #agentclass.py class B: def printMe(self): print "I am B" def printOk(self): print "B say:OK" class C: def printMe(self): print "I am B" def printOk(self): print "C say:OK" class A: __realobj__ = B() def __getattr__(self,attr): return getattr(self.__realobj__,attr) def printMe(self): print "I am A"

if __name__ =="__main__": a=A() a.__realobj__ a.printMe() a.printOk()

= B()

a.__realobj__ a.printMe() a.printOk()

= C()

$1(J: $ python agentclass.py I am A annCharles@tom.com

166 , 208

Python ÆS)P


§1.13 a B say:OK I am A C say:OK 3ڇ~f¼§class instance a ĂšŒ¤å class object A ¼½Ă‚ printMe § Šâattribute |¢ÂŽ{§__getattr__ ´ Â˜Ăš§XJ3class instance ¼Úن ½Üm ¤å class object ÂĽĂ‘vkĂŠ attribute §@orڇattribute =g‰ý ʖ__realobj__ Ăž" UC__realobj__ Ă’ÂŒÂąUCa ʖ ¤|Âą attribute "ÂŒÂąw‰´Ă„ U§ ½Ü`^|ĂœĂŠÂ– Â?ª¢y UÂŤ" Ă?Â?UÅ› Ă’´dattribute |¢ÂŽ{¢y § __getattr__ ŸêĂ’´ÂŽ{ ÂĽ  Â˜Â‡ €§|^ΤÂŒ¹¢yUÅ›" ^setattr Â?ʖÄ O\attribute ~f: #dynamicattr.py class A: def __init__ (self,**kws): for k,v in kws.items(): setattr(self,k,v) def DumpObj(self): for k,v in vars(self).items(): print "%10s:%s"%(k,v) if __name__ =="__main__": D = {"one":1,"two":2,"three":3} a=A(five=5, six=6) for k , v in D.items(): setattr(a,k,v) DumpObj(a) $1(J: python dynamicattr.py one:1 annCharles@tom.com

167Â?, 208Â?

Python ÆS)P


˜ Python0 six:6 five:5 three:3 two:2 lڇ~fÂŒÂąw §Â˜Â‡ĂŠÂ– Ă’´Â˜Â‡dictionary p?êâ( " ʖó‚ ¢y Â&#x;o´Ê–ó‚ºÊ–ó‚Ò´) ʖ /Â?"3C++ ¼§Â? (š )¤Ă˜Ă“ ʖ§Ì^ ĂŠĂľÂ?{)¤Ê–" 3Python ÂĽÂ?kaq Â?{§Lˆ Â?\;n§ Ă?3uPython ÂĽclass Â?´Â˜ ‡Ê–"" ~f: #objFactory.py class ObjFactory: def __init__(self,clsobj=None,*args,**keyargs): self.clsobj = clsobj and clsobj or self.__class__ self.args = args self.keyargs= keyargs def createObj(self): return self.clsobj(*self.args,** self.keyargs) class testClass: def __init__(self,value1,value2,*args,**keyargs): for k,v in keyargs.items(): setattr(self,k,v) self.args = args self.value1 = value1 self.value2 = value2 def DumpObj(self): for k,v in vars(self).items(): print "%10s:%s"%(k,v) if __name__ == "__main__": f = ObjFactory(testClass,100,200,300,one=1,two=2,three=3) DumpObj(f.createObj()) annCharles@tom.com

168Â?, 208Â?

Python ÆS)P


§1.13 a

$1(J: % python objFactory.py one:1 value2:200 value1:100 args:(300,) three:3 two:2 `²: 1. callableobj(*args,**keys) ‚ ÂŞ ´ › Š ( š N ^ Â? ÂŞ "args ´ ˜ ‡tuple , keys ´Â˜Â‡dictionary "Ăš N^Ÿêcallablobj žÿ§callableobj largs ÂŻ K¤kŒ‡ ĂŤĂŞ(positional argument)§¯Â?e ŠÂ??¿‡ê ĂŤĂŞ(arbitrary argument)§keys ŠÂ?i;ÍꧽÜ 'Â…iĂŤĂŞ(keyword arguments)"ڍÂ?ÂŞ 'N^apply ŸêÂ?\Â?B" 2. UCó‚Ê–f §Ă’ÂŒÂą) Ă‘Ă˜Ă“ ʖ5"~X˜‡?)è §S¼§XJ|Âą Ă˜Ă“ ?)èÂ?Y§@oÂŒÂąÂŠâŠÂ‡Ăž &E§Ă„ )¤?)èÏÊ–§@o?) è ?nL§Ă’ÂŒ¹­^ "XJÂą ‡|ÂąÂ?Ăľ ?)èÂ?Y§Â?‡½Ă‚# ?) èÏÊÂ–Ă’ÂŒÂą" ­1 iter

a§4ʖwĂĽ5–S“Ï

Â&#x;o´S“Ï(iterator) ºŒĂŒÂ‡^uH{˜‡êâ( § ڇêâ( ˜„´´Â˜ ‡NϧÙ¼Â?škĂŠĂľ ʖ" ~^ S“ÏÒ´sequence S“Ï" for i in "abc": print i 3ÂŚ^for ŠÊ žÿ§¢SN^ in ¥Ê– iter() Â?{§ ˜‡S“ÏÊ –i §, Ă˜ä N^i.next() Â˜Â‡ĂŠÂ–§Â† u)StopIteration É~" eÂĄ ~f`² for ŠÊ ś" >>> s = ’abc’ >>> it = iter(s) >>> it <iterator object at 0x00A1DB50> >>> it.next() annCharles@tom.com

169Â?, 208Â?

Python ÆS)P


˜ Python0 ’a’ >>> it.next() ’b’ >>> it.next() ’c’ >>> it.next() Traceback (most recent call last): File "<pyshell#6>", line 1, in -toplevelit.next() StopIteration ½Ă‚˜‡|ÂąS“Ï class object ĂŠ{Ăź"­1__iter__() §ÂˆÂŁÂ˜Â‡object§Ú‡ ʖ|Âąnext() attribute "XJclass object knext Â?{§@o__iter__() Â?ÂŒÂą ÂˆÂŁgC" ~f: #itertor1.py class Container: def __iter__(self): return TestIter(0,5) class TestIter: def __init__(self,start=0,end=10,step=1): self.start=start self.end = end self.step = step def next(self): if self.start == self.end: raise StopIteration try: return self.start finally: self.start = self.start + self.step if __name__ == "__main__": c = Container() for i in c: print i annCharles@tom.com

170Â?, 208Â?

Python ÆS)P


§1.13 a $1(J: 0 1 2 3 4 try ... finally ÂŠÊ´Ă‰~?nŠÊ" ڇ~fÂĽ^ÂˆÂŁÂ˜Â‡# ʖ§TestIter(0,5) §Ú‡Ê–|Âąnext() attribute " e¥Ú‡~f¼§__iter__() ÂˆÂŁĂŠÂ– § ʖ q|Âąnext() Â?{"ÂŒÂą Ă“ J" #itertor1.py class Container: def __iter__(self): self.index = 0 return self def next(self): if self.index == 5 : raise StopIteration try: return self.index finally: self.index = self.index + 1 if __name__ == "__main__": c = Container() for i in c: print i S“Ï Š^´ŠlH{ÂŽ{ĂšNÏêâ( "k NÏêâ( ´ÊE, §~X ä§Ăœ êâ( "H{ÂŽ{´þþ §Œ^SÂ“ĂŹÂŒÂąĂ›ĂľÂŽ{ [!§4ÂŚ^ ܹĂšÂ˜ /ÂŞN^"ڍÂ?{4§S LˆC ĂŠ{'§Â˜Â—" \½Ă‚˜‡Lˆ ä( žÿ§ÂŒ¹½Ă‚Ă˜Ă“ Â?{§ÂˆÂŁĂ˜Ă“ S“줢yĂ˜ Ă“ H{Â?ÂŞ" for node in tree.leftfirst(): print node for node in tree.rightfirst(): print node annCharles@tom.com

171Â?, 208Â?

Python ÆS)P


˜ Python0 ´§Ă?~½Ă‚˜‡S“Ï žÿ§Ă‘‡Œ^˜‡CĂž5 Âą c  Â˜§~XÞ¥~ fÂĽ self.count self.index §ÂŒU„‡kÂ˜Â‡Ă˝ êâNϧÂŒÂą^self.index l ÂĽ Ă˝ k^ ʖ§ Ă˜´{Ăź self.index §Ă„K^range ŸêĂ’ÂŒÂą " XJ\‡ S“ϴÊ{Ăź ÂŽ{§Â„‡½Ă‚AO CÞ§self.index §AO Âź ĂŞself.next Ăš ÑÉ~raise StopIteration §Ú ÒÊ̆ §Ă?Â?\ S“Ï ÂŽ{ ´Xd {ߧĂ˜Â–u‹ÄZ{§¤¹e¥Ú‡Â?{AOk^§âŠ )¤ÏGenerator" ~X: def gen(): yield 1 yield 2 yield 3 yield 4 g = gen() print g.next() print g.next() print g.next() print g.next() print g.next()

# # # # #

‹< 1 ‹< 2 ‹< 3 ‹< 4 ÑÉ~

ÂŚ^yield ÂŠĂŠÂŒÂąMĂŻÂ˜Â‡Generator"yield ŠÊÂ?UĂ‘y3Ÿê¼"XJÂ˜Â‡Âź ĂŞÂĽkyield Šʧ@oڇŸêĂ’ ‰generator "- yield ÂŠĂŠÂƒ §ŸêÂˆÂŁÂ˜ ‡iterator §¿Â…P4v &E§P‰¼ä:"|^Ăš &E§§SÂŒÂąl¼ä:?­# $1§ 3ÂŚ^iterator žÿ§XJN^next() Â?{§@oĂ’ÂŹĂ’l¼ä:?­#$1" XJgenerator ŸêÂˆÂŁ §Ă’gĂ„ Ă‘StopIteration É~" 3list comprehension ś¼§¢SÂ?ÂŒÂą^S“Ï"~X: >>> x = [ i*i for i in gen()] >>> x [1, 4, 9, 16] w,˜‡~f: #generator1.py def reverse(data): for index in range(len(data)-1, -1, -1): yield data[index] annCharles@tom.com

172Â?, 208Â?

Python ÆS)P


§1.13 a for char in reverse(’golf’): print char $1(J´: f l o g 'Â…3uyield ŠʧŒ Âżg´`§ 1. ff?\ĂŒÂ‚ žÿ§Ă?ŠN^reverse()" 2. reverse() ¼‰1 yeild ŠÊ žÿ§reverse() 6ĂŠ§ÂˆÂŁÂ˜Â‡êâÊ–" 3.  for êâ§Â‰1for ĂŒÂ‚NS Šʧ?1?nêâ" 4. Â˜Ă“ĂŒÂ‚(ĂĽÂƒ §lyield 6ĂŠ /Â?§UY‰1reverse() ÂĽ ŠÊ"XJq yield Šʧ@o2‰¹ÞÜŠ" 5. † reserver()ˆ£§for ŠÊâ ~(ĂĽ" 3zgI‡N^next žÿ§Ă’ÂˆÂŁyield ŠÊ ÂĄ Lˆª§§S6ĂŠ§, for ÂĽ ŠÊUY$1§eg2I‡next žÿ§UYlyield 6ĂŠ?§UY$1§Â† yield # êâ §2UY‰1" ڍLˆÂ?ÂŞÂŹ3ŸêÂˆÂŁ žÿgĂ„ Ă‘StopIteration É~" Â? Â?[ yield ŠÊ ^{§eÂĄ ~f‰ ˜ ?U§Â?´O\ ˜ ‹<Š ʧ^u`²§S ‰1^S" #generator2.py def reverse(data): print "reverse begin" for index in range(len(data)-1, -1, -1): print "begin yieding " + str(index) yield data[index] print "end yieding " + str(index) print "reverse returned" for char in reverse(’golf’): print "begin getting a char " print char print "end getting a char" annCharles@tom.com

173Â?, 208Â?

Python ÆS)P


˜ Python0 $1(JÂľ reverse begin begin yieding 3 begin getting a char f end getting a char end yieding 3 begin yieding 2 begin getting a char l end getting a char end yieding 2 begin yieding 1 begin getting a char o end getting a char end yieding 1 begin yieding 0 begin getting a char g end getting a char end yieding 0 reverse returned XJ3for ÂĽ- break Šʧ@o§SĂ’Ă˜2ÂŁ yield 6ĂŠ /Â?§ ´Â† a Ă‘ĂŒÂ‚§Â‰1ĂŒÂ‚ ÂĄ ŠÊ "~X: #generator3.py def reverse(data): print "reverse begin" for index in range(len(data)-1, -1, -1): print "begin yieding " + str(index) yield data[index] print "end yieding " + str(index) print "reverse returned" for char in reverse(’golf’): print "begin getting a char " annCharles@tom.com

174Â?, 208Â?

Python ÆS)P


§1.13 a print char if char == ’l’ : break print "end getting a char" $1(J: reverse begin begin yieding begin getting f end getting a end yieding 3 begin yieding begin getting l

3 a char char 2 a char

§1.13.11 new style class new style class ´Python 2.2 #JĂ‘ ĂľU"Ă?dÂƒĂŠunew style class §Þ¥0 class object § ‰classic class " XJ˜‡class object yk´â€œobjectâ€? §@oڇclass object Ă’´new style class " “objectâ€? ´Â˜Â‡class object Âśi"Â?Ă’´`§XJ˜‡class object † U½Üm UÂŤâ€œobjectâ€? §@oĂ’´new style class " † UÂŤ new style class ~X: class newClass(object) m UÂŤ ~fX: class newClass(dict) "Ă™§ Xint, float, list, dict, tuple, file §Ă‘´â€œobjectâ€? fa" new style class äkclassic class ¤kA5" kÂĄX­0 new style class Ăšclassic class Ă˜Ă“Âƒ?" O\ ߇# methord ś static methord weÂĄ ~f" class AClass(object): def astatic( ): print ’a static method’ astatic = staticmethod(astatic) anInstance = AClass( ) AClass.astatic( ) # prints: a static method anInstance.astatic( ) # prints: a static method annCharles@tom.com

175Â?, 208Â?

Python ÆS)P


˜ Python0 3½Ă‚Ÿê

§Œ^ŠÊ

astatic = staticmethod(astatic) ÂŒÂąMĂŻÂ˜Â‡static methord " class instance Ăšclass object Ă‘ÂŒÂąN^static methord §J˜ " static methord ÚÊĂ?function A vkÂŤO" class methord weÂĄ ~f" class ABase(object): def aclassmet(cls): print ’a class method aclassmet = classmethod(aclassmet) class ADeriv(ABase): pass bInstance = ABase( ) dInstance = ADeriv( ) ABase.aclassmet( ) # prints: a bInstance.aclassmet( ) # prints: a ADeriv.aclassmet( ) # prints: a dInstance.aclassmet( ) # prints: a

for’, cls._ _name_ _

class class class class

method method method method

for for for for

ABase ABase ADeriv ADeriv

`²: class methord Ăšbound methord aq"bound methord ´gĂ„rclass instance ŠÂ?1Â˜Â‡ĂŤĂŞ"class methord ´gĂ„rclass object ŠÂ?1˜‡ꐤ Ă˜´class instance " ĂƒĂ˜´clsInstance.class_methord /ª§Â„´clsObject.class_methord / ª§ J˜ " O\ # AĂ?Ÿê new __init__ ´Ă?ŠzŸê§Ă˜´ EŸê"3N^__init__ Ÿê žÿ§Ê–Ž ²MĂŻĂ? "#O __new__ Ÿê§´ý EŸê" clsInstance = clsObject(...) du clsInstance = clsObject.__new__(clsObject,...) 5Âż §__new__ 1Â˜Â‡ĂŤĂŞĂ˜´Â˜Â‡class instance § ´Â˜Â‡class object "ÂŚ% @Ă’´Â˜Â‡Â˜Â‡class methord §Ă˜^ÂŚ^ annCharles@tom.com

176Â?, 208Â?

Python ÆS)P


§1.13 a __new__ = staticmethod(__new__) 5AO(²Œ´Â˜Â‡class methord " object.__new__ %@Ċ´MĂŻÂ˜Â‡ĂŠÂ–§, instance "

N^__init__ §ÂˆÂŁÂ˜Â‡class

­1__new__ žÿ§~~N^Ia(Xobject, list, tuple, dict, file ) __new__ Ÿê§, §2ŠÙŒ\‡Z ÂŻÂœ" ˜‡;. ~fĂ’´ÂˆÂŁÂ˜Â‡Ž² 3 ʖ§¢ySingleton design pattern "~ fÂľ class Singleton(object): _singletons = { } def _ _new_ _(cls, *args, **kwds): if not cls._singletons.has_key(cls): cls._singletons[cls] = object._ _new_ _(cls) return cls._singletons[cls] ڇ~f¼§Singleton z˜‡fša§Â?UkÂ˜Â‡ĂŠÂ–§Â?Ă’´`§XJclsobj1, clsobj2, ..., clsobjn , Ă‘´Singleton fš"@oclsobj1 ¤kclass instance Ă‘´ Ă“Â˜Â‡object §clsobj2 ¤kclass instance Ă‘´Ă“˜‡object §... §clsobjn ¤ kclass instance Ă‘´Ă“˜‡object "Ă˜Ă“fš§Xclsobj1, Ăšclsobj2 class instance Ă˜´Ă“˜‡object " getattribute __getattr__ ڇAĂ?Ÿê3attribute |¢ÂŽ{¼§´ Â˜'" #O__getattribute__ ´1˜'§Â?Ă’´Œ: ¤kattribute Ăš^žŒ" new style class class instance A5 property attrib = property(fget=None, fset=None, fdel=None, doc=None) ÂŒÂąÂ?˜‡new style class instance O\˜‡attribute § ‰attr " fget ´Ă–property žÿ§N^ bound methord "Ă˜ Ă‚ĂŤĂŞ"None LÂŤproperty Ă˜ÂŒĂ–"fset ´ property žÿ§N^ bound methord " Ă‚Â˜Â‡ꐤLÂŤ \Â&#x;o"None LÂŤproperty Ă˜ÂŒ "fdel ´íĂ˜property žÿ§Â?Ă’´N^del obj.attr ŠÊ žÿ§N^ bound methord "Ă˜ Ă‚ĂŤĂŞ"None LÂŤproperty Ă˜ ÂŒĂ­"doc LÂŤdoc string " ~f: annCharles@tom.com

177Â?, 208Â?

Python ÆS)P


˜ Python0 class Circle (object): def _ _init_ _(self,radius): self.radius = radius def getArea(self): return self.radius * self.radius * math.pi def setArea(self,value): self.radius = math.sqrt((value/math.pi)) area = property(getArea,setArea,doc=’area of the circle ’) ڇ~f¼§XJc ´Â˜Â‡Circle ˜‡class intance "@o print c.area # N^ c.getArea c.area = 100 # N^ c.setArea(100) print c.area.__doc__ # ‹< area of the circle " __slots__ ´Â˜Â‡sequence (˜„´tuple )§Ă™ÂĽz˜‡ ƒ´Â˜Â‡string "ڴ˜‡ Jp Ç Â?{"Ă?Â?object name space ´Â˜Â‡dictionary §´Ă„ ÂžĂšÂşÂ˜ S §Ú Ç$"k __slots__ ƒ §object name space Ă’´Â˜Â‡ ½S ÂŒ §Ă“ž§object Â?Ă˜k__dict__ 5LÂŤname space " object #ĂŻ attribute Âśi7L´__slots__ ÂĽ Âśi" ½Ă‚__slots__ Ă˜ u½Ă‚attributes , „‡MĂŻÂƒ

âU^"

~f: slots — >>> class OptimizedRectangle(object): ... __slots__= ’width’,’heigth’ ... >>> r = OptimizedRectangle() >>> r.width # ½Ă‚ __slots__ Ă˜ u½Ă‚ attribute Traceback (most recent call last): File "<stdin>", line 1, in ? AttributeError: width >>> r.width,r.heigth=1,2 >>> print r.width,r.heigth 1 2 >>> r.high = 100 Traceback (most recent call last): File "<stdin>", line 1, in ? AttributeError: ’OptimizedRectangle’ object has no attribute ’high’ annCharles@tom.com

178Â?, 208Â?

Python ÆS)P


§1.13 a ڇ~f¼§MĂŻhigh ´Ă˜#N " __slots__ Çp ś§´¹ã+Ă„ MĂŻattribute A5Â?“d " Â?k3S ÂĽĂ“ÂžÂŒĂž 3Ăš class instance žÿ§ÂŒÞ´Â?Az Ăš ĂŞĂž ?§ Ă˜´AZ‡Ú ĂŞĂž?§ Â…z˜‡instance ‡!ÂŽA›‡i!§Ú Jp Ç J²w"Ă„KĂ’vk7‡ " new style class ÂĽ Per-instance methords ˜‡class object ˜‡class instance ÂŒÂą ”½Â˜Â‡attribute ?ÂżÂ˜Â‡function object " ~X: >>> ... ... >>> >>> >>> >>> 100

class AClass: pass a = AClass() fakeGetItem=lambda idx:idx a.__getitem__=fakeGetItem a[100]

ڇ~f¼§a ÂŒÂąrAĂ?Ÿê__getitem__ §Â”½ ?ÂżÂ˜Â‡ŸêÞ§ ´Ú ž§a.__getitem__ Ă˜´Â˜Â‡bound methord § ´Â˜Â‡ĂŠĂ?Ÿê§Â?Ă’´`§ŒĂ˜ UgĂ„rclass instance ŠÂ?1Â˜Â‡ĂŤĂŞ" new style class Ăšclassic class 3?nĂš­1ĂśÂŠĂŽÂƒ' N^AĂ?Ÿêk¤Ă˜Ă“" new style class ´k3class instance ¤å class object name space ÂĽ|¢AĂ?Âź ê§ Ă˜ÂŹ3class instance name space |¢" classic class „´UĂŹ 5 |¢ÂŽ{§vkÂ&#x;oAĂ? ?n§Ă’Â”ĂžÂ˜Â‡~f" ~X: >>> class NewStyleClass(object): ... pass ... >>> a = NewStyleClass() >>> a.__getitem__=fakeGetItem >>> a[100] Traceback (most recent call last): annCharles@tom.com

179Â?, 208Â?

Python ÆS)P


˜ Python0 File "<stdin>", line 1, in ? TypeError: unindexable object >>> a.__getitem__(100) 100 ÂŒÂąw §ÜŠÎ­1 žÿ§new style class ==ÂŹ3class object ÂĽ|¢AĂ? Âź ĂŞ " ´ § X J Ă˜ ´ Ă? Â? Ăś Š ĂŽ ­ 1 § † N ^__getitem__ § „ ´ Ăš Ă™ ÂŚattribute |¢ÂŽ{˜— " new style class Ăľ ­UÂŤ  Â› list, dict, file ʖ¥Â?SÂ˜ĂŠÂ–"Œ‚U†¤ knew style class Ă„a“objectâ€?§3þ­U¼§ þÂ?UӞUÂŤÂ˜Â‡SÂ˜ĂŠÂ–Ăš ˜‡“objectâ€? " new style class Ăš classic class methord |¢ ^ SĂ˜ Ă“ classic UĂŹattribute | ¢ÂŽ{§|¢Â˜Â‡methord "~X: class D: pass class B(D): pass class C(D): pass class A(B,C): pass UĂŹ|¢ÂŽ{§classic class |¢^S´A, B, D, C, D " class D(object): pass class B(D): pass class C(D): pass class A(B,C): pass new style class |¢^S´A,B,C,D,object "Â?Ă’´2Ă?`k|¢" new style class Ăš classic class N ^Ia Â?{Ă˜Ă“ classic class ÂĽN^Ia Â?{§ Â˜Â„ÂŚ^unbound methord "~X: annCharles@tom.com

180Â?, 208Â?

Python ÆS)P


§1.13 a class A: def met(self): print ’A.met’ class B(A): def met(self): print ’B.met’ A.met(self) class C(A): def met(self): print ’C.met’ A.met(self) class D(B,C): def met(self): print ’D.met’ B.met(self) x=D() x.met() 3ڇ~f¼§B.met(self), C.met(self) Ă’´unbound methord ^{" ´¯K ´§Ú A.met Ă’ÂŹ N^Ăźg" $1(J´: D.met B.met A.met C.met A.met new style class )Ăť Â?{Ă’´§Œ^super "super(clsobj,obj) ÂŹÂˆÂŁÂ˜Â‡AĂ? clsobj Ia" ¡Â‚^ super(clsobj,obj).somemethord(...) |¢somemethord žÿ§|¢^SĂšÞ¥Ú |¢^S´Â˜ " ~X: class A(object): def met(self): annCharles@tom.com

181Â?, 208Â?

Python ÆS)P


˜ Python0 print ’A.met’ class B(A): def met(self): print ’B.met’ super(B,self).met( class C(A): def met(self): print ’C.met’ super(C,self).met( class D(B,C): def met(self): print ’D.met’ super(D,self).met( x=D() x.met()

)

)

)

$1(J´¾ D.met B.met C.met A.met 3ڇ~f¼§super(D,self).met() |¢met ^S´B,C,A "Ăš §Ă’vkĂš ‡¯K "ïƹ new style class Ă‘^ڍÂ?{N^Ia methord "

§1.14 É~?n(exception) §1.14.1 Â&#x;o´Ă‰~?n§Â?Â&#x;o‡kÉ~?n É~?n´Â˜ÂŤĂ‘†?n ś"˜½Â‡ĂŠĂ‘†?n‰upĂ?­Ă€§Â˜Â‡rF S §S “輧¿á ц?n§XJĂ˜Â‡Ă‘Â†?n§@o “è 5 ÂŹ ĂŠĂľ"\ÂŒ ¹Ê˜‡‘8 ~f§wwpÂĄkĂľÂŒ '~ “è´Ă‘†?n§Â„kĂľÂŒ'~´Nà “ è"\ÂŒUÂŹuyĂ˝ Zš “èĂ“ĂŠ '~"Ă’ÂŽÂ˜Â‡ ~$1 §S§Œ ÂŒĂœŠÂž m$1 “èÂ?´\¤ Â“è¼ 4 Â˜ĂœŠ" ´Ă˜UvkĂš “觌‚Ò–ž“

§²ÂžÂżvklÂŻ) óŠ§vkMEdŠ§ ´Ă˜UvkŒ‚§?Ă›<Ă‘ ž“è

­Â‡5"C ÂĽÂ†Ă˜?n Â?{´ int fun1() annCharles@tom.com

182Â?, 208Â?

Python ÆS)P


§1.14 É~?n(exception) { ... if ( open(...) == -1 ){ return -1; } ... } int fun2() { ... if (fun1()==-1){ return -1; } ... } int main() { ... if(fun2()==-1){ return -1; } } lڇ~f¼§¡Â‚ÂŒÂąw CŠó ц?nk‡¹eA‡A:Âľ • §S z˜?ч‰Ñ†?n§^5rÂ†Ă˜Ă? ĂžÂ˜?Ÿê" Ă?Â?. ŸêĂ˜ ATNo?nÂ†Ă˜§Â?kŸê N^ܧÂ?Ă’´Þ˜?ŸêâU §¤¹7LĂš ˜?˜? Ăž " Ăš ‘5 ÂŻK´§ ?Ă‘´ äц§Â“è ÂŒĂœŠĂ‘´Ă‘†?n" • §SĂ?LÂˆÂŁÂŠ5LÂŤÂ†Ă˜" Ăš ‘5 ÂŻK§ÂˆÂŁÂŠkĂœĂ‚"ÂˆÂŁÂŠĂ˜ Â‡ÂˆÂŁ ~ §SŽ‡ êâ§Â„‡ˆ ÂŁÂ†Ă˜G §Ú §§S“kÂŒUâ€?ÂŹrÂ†Ă˜G ¤ÂˆÂŁ êâ5?n"~X: unsigned int r; r=read(fd,buffer,len_of_buffer); for(i=0;i<r;i++){ // do something } annCharles@tom.com

183Â?, 208Â?

Python ÆS)P


˜ Python0 Úã§S§´Ê²w kÂŻK§XJread ц§ÂˆÂŁâˆ’1 ´§Svk ä§for ¤Â?kĂŒÂ‚" ,§Â˜Â„Ă˜ÂŹ Ă‘Ăš D “è§Êr DŠÂ?ÂŹk?Ăˆ´w§a. Ă˜Âš " ´Ú‡“è`² \“kÂŒUâ€? Ă‘Ăš “è§cĂ™´§S' ÂŒ ž ÿ§\ÂŒUk?U ,‡Ÿê ÂˆÂŁÂŠ ÂŻk ½"@o¤kŸê N^ÜÑkÂŒU Ă‘yĂš ÂŻK" • ц&E "Ă?Â?ÂˆÂŁÂŠ oĂŞÂ…§¤¹Ă˜U ‘Â?Ăľ ц&E"~XXĂšN ^read ÂˆÂŁâˆ’1LÑ†§Â„‡errno 5LÑ†è§Â„I‡ÙŒ ŸêrцèC ¤Â†Ă˜&E ŠiÂŁĂŁ" exception ś´-Â˜ÂŤĂ‘Â†?n Â?ª§ŒkÂąeA:: • Ăšreturn ˜ § ÑÉ~Ă“ ŒŸêÂˆÂŁ" • Ăšreturn Â?kÂŤO§XJreturn§Ÿê N^܏ ÂˆÂŁÂŠ§XJu)É~§Ÿ ĂŞ N^ĂśĂ˜ÂŹ ÂˆÂŁÂŠ" • gĂ„|ÂąÂ†Ă˜ Ăž "É~ÂŹ3ÌÒ¼•Þk §Â† k<Ă“٤XJ,‡Ÿê Ă‘

É~§ Ÿê N^Ăśqvk?nÉ~(ӟÉ~)§@oҖ3ŸêN^?u)É ~˜ §Ÿê N^ĂśÂ?ÂŹÂˆÂŁ" • òц?nĂšÂˆÂŁÂŠ ĂľUŠm"Â?‡ ÂˆÂŁÂŠ§@oÂŚĂ’´§SŽ‡ êâ§Ă˜ ÂŹkٌ¿g" ~X: def fun1() ... open file ... def fun2() ... fun1() ... def main() try : fun2() except exp : print "error message" return.

§1.14.2 Ă“Âźexception(É~) kߍӟÉ~ Â?{"1˜´ annCharles@tom.com

184Â?, 208Â?

Python ÆS)P


§1.14 É~?n(exception) try : ... # statements 1 except ExceptionType : ... # statements 2 ÂŁĂŁXe: • Ă„k‰1statement 1§XJvkexception u)§@oĂ’Â˜Âƒ ~§Ă’”vktry ŠÊ ˜ §UY‰1 ÂĄ ŠÊ" • X J u ) exception § @ o Ă’ rexception a . Ăšexcept Š ĂŠ ÂĄ ExceptionType ' §wexception a.´Ă„ĂšExceptioinType ˜—§ • XJ˜—§Ă’‰1statement 2" • XJĂ˜Â˜Â—Ă’Â•Â† ˆ£§rexception ‰Ÿê N^ܧ, Ă’Ăš ˜?˜? • Ăž §Â† ktry ŠÊӟ exception" • evk?Ă›try ÂŠĂŠÂŒÂąĂ“٤@o§SÒÉ~òĂ‘§3)ºÏ¼Â‰1 {§Ă’” Âąc ~f˜ §Â‹<Ă‘5É~u) Â?[&E"ÂŒÂą^1/0 w˜e ) 0Ă˜ É ~" Œ„§exception ´,˜Ÿêreturn Â?ª§CŠó½Üٌvkexception ś ÂŠó§ ŸêÂ?kĂ?LÂˆÂŁÂŠ5Â?²Ÿêц§¤¹z˜?Ÿêчu Ÿê ÂˆÂŁÂŠ"exception śÒ´JøĂ˜ ÂˆÂŁÂŠÂƒ ,Â˜ÂŤĂ‘Â†?n Â?{"ڍÂ?{|ÂąÂ†Ă˜ •Þk § XJ,˜?ŸêĂ˜ TNo?nÂ†Ă˜§@oĂ’Ă˜?n§3‰Â?ĂžÂ˜?Ÿê?n"cĂ™ ´lib ÂĽ module §ŒÂ‚ ц?nÂŒþêĂ‘ Ă‘exception "˜‡try ÂŒÂąkþ‡except ŠÊ" try : ... # statements 1 except (ExceptionType1,ExceptionType2) : ... # statements 2 except (ExceptionType3,ExceptionType4) : ... # statements 3 except: ... # statements 4  Â˜Â‡exceptvkÂ?½exception a.§LÂŤĂ“Âź?Ă›a. exception"try ÂŠĂŠÂŒÂą k˜‡else Šʧ˜½Â˜3 §LÂŤvku)exception žÿ‰1else ‘ ˜ Š ĂŠ"~X: try: f = open("/home/chunywang/tmp/test.py","r") annCharles@tom.com

185Â?, 208Â?

Python ÆS)P


˜ Python0 except IOError: print "can not open file" else: for i in f.readlines(): print i LÂŤXJ‹mŠÂ‡¤þ§Â?Ă’´`§Â‹mŠÂ‡ žÿvku)É~Ă’Ă–ŠÂ‡"Ă?L' Âąe A‡~f§ÂŒÂą Ăš ‰ Ă??" try: f = open("/home/chunywang/tmp/test.py","r") for i in f.readlines(): print i except IOError: print "can not open file" ڇ~frĂŠĂľÂŠĂŠĂ‘Â˜3try ¼§Ú ‰ {§Â‘5ÂŻK§XJĂ‘y IOError§Â?Ă˜ ˜½´open žÿ ) §readlines() Â?ÂŒÂą )ڇexception"¤¹Ă˜Â‡rÊþŠÊ ˜3try ¼§Ă?Â?Œ‚¼k Â?ÂŹ )exception§ Ăš exception ÂżĂ˜´\Ž‡ §3 ~f¼§exceptÂ?Ž‡‹mŠÂ‡Ă‘† exception§ Ă˜´Ă–ŠÂ‡Ă‘†"XJ‡?nĂ–ŠÂ‡ ц"ÂŒÂą try: try: f = open("/home/chunywang/tmp/test.py","r") except IOError: print "can not open file" else: for i in f.readlines(): print i except IOError: print "read faid" $–Ò” 5 ~f˜ §Ă˜Â‰?Ă›?n§4ĂžÂ˜?Ÿê ?n"½Ü: try: f = open("/home/chunywang/tmp/test.py","r") except IOError: print "can not open file" else: try: for i in f.readlines(): print i except IOError: print "read faid" annCharles@tom.com

186Â?, 208Â?

Python ÆS)P


§1.14 É~?n(exception) ,˜‡' ~f´ try: f = open("/home/chunywang/tmp/test.py","r") except IOError: print "can not open file" return None for i in f.readlines(): print i ڍÂ?{¼§XJĂ˜\return Šʧ@o3ŠÂ‡Â‹m”} žÿ§readlines „‰1§ Ăšw,´Ă˜1 §Ă–˜‡vk‹m ŠÂ‡§´Êä §gC‰gCÊ̆" ´return Š ĂŠÂ? Â›§Ă?Â?Ÿê† ÂˆÂŁ §Â?N\ÂżĂ˜ÂŽĂšoZ"އ~f§b ÚãŠʴ^5l ˜ŠÂ‡ÂĽĂ– ˜ XĂšꐤXJÂ‹Ă˜m ˜ŠÂ‡§Ă’ ˜Â?"ŽŠ", 2ŠÙŒÜ Š" Ă?^eÂĄ Â?Y" try: f = open (" ˜ŠÂ‡") except IOError: ˜"ŽŠ else : lŠÂ‡ÂĽĂ– XÚÍê #y3XĂšÍê´k

ŠÙŒÜŠ XJĂ˜^else Â?{§Â„k˜‡Â?Y´ isOpen=false try: f = open (" ˜ŠÂ‡") isOpen=true except IOError: isOpen=false if isOpen : lŠÂ‡ÂĽĂ– XÚÍê else: ˜"ŽŠ #y3XĂšÍê´k

ŠÙŒÜŠ ڍÂ?{O\ ˜‡# CÞ§Ăšelse ŠÊ' §Ă’vk@o˜Ă&#x; "1 É~?n Â?{´ annCharles@tom.com

187Â?, 208Â?

Python ÆS)P


˜ Python0 try: ... # statements 1 finally: ... # statements 2 ڍÂ?ÂŞĂ˜UĂš1Â˜ÂŤÂ?ª¡^§Â?Ă’´`§Ă˜U‘kexcept Ăšelse § Ă?r§w¤ ,Â˜ÂŤÂŠĂŠ"ĂƒĂ˜´Ă„u)exception §Â„´return ÂŠĂŠÂˆ£§finallyfĂŠstatements 2 я‰1§ >>> def fun(): ... try: ... print "ok" ... return 1 ... finally: ... print "clean up" ... return 1 ... >>> fun() ok clean up 1 >>> ڍÂ?{¡ĂœuÂşÂ˜] "XJ˜‡Ÿêkþ‡/Â?return @o҇3z˜‡returnƒc ? A Ă“ ÂşÂ˜] “è§X'4ŠÂ‡§'4 äÍ "finally Â?{Jø

˜‡3ŸêÂˆÂŁÂƒc§Â‰1˜ “è§5'4] §ŸêÂˆÂŁÂŒU´Ă?Â?return Šʧ½ Ăśu) vk Ă“Âźexception

§1.14.3 Ă‘exception raise ŠÊ^u Ă‘exception§3 Ă‘exception žÿ§ÂŒ¹´?Ă›object§^uÂ? [ÂŁĂŁÂ†Ă˜a." >>> from UserList import * >>> try: ... raise UserList([1,2]) ... except UserList,arg: ... for k in arg: print k ... 1 2 annCharles@tom.com

188Â?, 208Â?

Python ÆS)P


§1.14 É~?n(exception) 3except ÂĽÂ?‡exceptionTypeĂšobject a.˜—§Ă’ÂŒÂąĂ“ŸÚ‡exception "a. ˜— Âżg´Â?object ´Â‰a. ˜‡instance"XJ˜‡object ¤å class UÂŤ ٌ class§@oڇobject ÂŒ¹´þ‡a. instance§Ú a.Â?)object ¤å class I a§Ia Ia§Ia Ia Ia... except Ă˜ ÂŒÂąÂ?½exception a.§Â„ÂŒÂą Ă‚ Ă‘5 object" ĂžÂ˜Â‡~fÂĽarg Ă’´raise ŠÊ Ă‘5 UserList([1,2]) Ăš §Ă’ÂŒÂąk´L & EÂŒÂą^5£ãц Ă?"˜„5`§Ă‘´ Ă‘Exception Ăš§ fa§lĂƒÞ¼ÂŒÂą ĂŠĂľException a.§X: KeyError§IndexError§IOError " ´pythonŠ Ăłvk Â›§\ÂŒÂą Ă‘?Ă›a. ʖ"^rÂŒÂągCMĂŻÂ˜Â‡Exception fa§5 LÂŤ^rf½Ă‚ exception"raise ÂŠĂŠÂ„ÂŒ¹´raise classname,objectname /ª§ Ù¼objectname ÂŒÂąĂšclassname vk˜:'X§ ,Ăš Â‰ĂŠĂ˜²Âœ§Â˜Â„classname Ăšobjectname„´k'X §^5L²\ §SÂĽ Ăœ6'X" classname ĂŠAexcept ŠÊ¼ exception a.§objectname ĂŠAexcept ŠÊ¼ arg >>> try: ... raise KeyError, "hello" ... except KeyError, arg: ... print arg ... hello Œ„§ ÑÚӟexception Jø Â˜ÂŤÂ?B ц?nś"ŸêĂ˜^3Ă?LAĂ? ÂˆÂŁ Š5Ă? ĂžÂ˜?Ÿê£Ÿê N^Ăś)u) Â†Ă˜§ ´Ă?Lraise exception Â?ÂŞ" ÂˆÂŁÂŠĂ’´Ÿê ~ÂˆÂŁ žÿATÂˆÂŁ Ă€Ăœ" ڍÂ?{ÂŒÂą\ÂŻmu„Ă?§3mu Ă?Ă?§ÂŒÂąĂ˜^?n?Ă›Â†Ă˜§¹\¯§S . mu„Ă?" ~ §S¼§kÊþ“è´Ă‘†?n§Â˜?˜? ?n"XJ KĂš ?n§Œ §SwĂĽ5ĂŠÂ˜Ă™§² " ˜‡Â?šÊ ц?n §S .ÂĽy‡^r žÿ§Œ+ÂŚ Ă˜´ÊrF§ ´ÂŒÂąkÂ˜Â‡Ă˝ ÂŒ¹Œ^ §SŠÂ?ĂŤ §^5Ă‚8^r IΤ á^ r IŒ§Ú ÂŒÂą~ ‘8 Âşx" ƒ‡§XJ˜‡§Smu ĂŠĂˆ§Â?šÊþ ц?n§Â?ĂŠrF§ ´¼y‡Â?r žÿ§%uy§ 5@Ă˜´Â?rŽ‡ §@´ÊĂ&#x;Ă” §Â”“§L¤<üÔü ÂŻÂœ" –uц?n§ÂŒÂą3Âą O\§Ă?Â?Ÿê ÂˆÂŁÂŠĂšĂ‘Â†?nvk'X§§S ĂŒZ ´Ă˜I‡UC §§S ?n6§Ă˜I‡Cz"Â?Ă’´`§ÂŒ¢ ĂŒN( ´Ă˜^C §Â‡ ‰Â?´V<\ "¡ÂŽxxÂ?´kĂ“ n§Ă‘´kx‡Ó+§, 2Â˜ĂšÂ˜Ăš[z" annCharles@tom.com

189Â?, 208Â?

Python ÆS)P


Python0 XJvkexception Å {(~XC ó)§\ÒI trace (|¢) .´= ¼ê £

ا ´ Ø Þ§, 3¤kN^ù ¼ê / Ñ\ ä§þ Ø §XJ k ¼êk {ÏL £ 5þ ا~X§ ¼ê £ ´ iÎ(byte§ õ0 – 255)§L«,256 « ~G §y3 2O\eZG L«Ñ §@o o?U¼ê £ a.§ oO\# ëê§^u £ Ø"o ´I ?U §¯¤± §?U ´§Smu ý " Ñyù«¯K ÏÒ´“ £ Ø==´ £ ”" ^exception Å §Ò ±3I Ñ ?n / §O\try é"Ò ´ è § @pk»Ò =p§ Ø´3?Û UX» / Ñ è §@ ¬é@ §\ XÚ¥<A Ñ´ è § ý Z¹ <%é "½ö`Z¹ <Ó É Ôö§ oê § § ´· “ ¬©ó”´ k? ) ª" ^BJ e§Exception Å I Ä S +nÅ §½ö`gÄé £ÂÅ " C++ ¥ kException Å § ·ú ØÐ^§XJ\ Ñ é §@oX5£Âù é =º ¢yù ª§¬r 5éE, C++ §t \E, "Python§Java ÒÐõ "Ø^ú% ÑÉ~¬ )S ¦" ÆSPython L§§ÚÆSC++ ÚJava L§§4·a §ÆS ó´g §ÆS «?§g â´Ì "k ó , A5 ¡Ñ k ?§g 3Ù¥" ó´g 1N" Python á  é õ k ? ? § g § X ó ó( glue language )§ Perl§VB Script §Java Script §Bash" X . m u( prototype development )" X ¡ é (Object Oriented)§ C++§Java"Xra.(strong type) §Ä a.(dynamic type) § Scheme§LISP"X KL ª(regular expression)§ Perl§Sed§Awk"XWeb ÑÖ ì?§§ Perl" kDoc String§lambda¼ê§ LISP" k¼ê Cëê§?¿ ê ë꧷¶ëê§ C++§Java §VB" ¦ k gC A5§¦r ?ª { Ü©§ Ù´Xd r N Ö 5"

annCharles@tom.com

190 , 208

Python ÆS)P


1 Ă™

m uPython ÂŚ ^ Ăł ä §2.1 ÂŚ^Emacs ?6Python §S Ă™b½^rÂŚ^LEmacs §Emacs ´Â˜Â‡Ă?Âś §Smu‚¸§Ă˜==´Â˜Â‡?6 ĂŹ" python mode ´Emacs ÂĽ ˜‡?6python §S ĂŒ ÂŞ"

§2.1.1 SCpython mode XEmacs 21.4.4 ^rÂŽÂŻ §Œg‘kPython mode " XJ\ XÚ¼vkpython mode {§UĂŹeÂĄ SCĂš½: 1. e1python-mode.el ŠÂ‡§3Python 2.3 SCÂ?¼§Misc 8š¼škڇŠÂ‡" Â?ÂŒÂą eÂĄ ÂŒe1 http://www.python.org/emacs/python-mode/python-mode.el 2. € python-mode.el ˜‡8š¼§~X: cp python-mode.el ~/emacs/ 3. 3~/.emacs ÂĽO\eÂĄ SN" ;; Python ;; ;; 4 emacs ÂŒ¹Ê python-mode.el (add-to-list ’load-path "~/emacs") ;; ‹m *.py ŠÂ‡ žÿ§gĂ„\1 python mode annCharles@tom.com

191Â?, 208Â?

Python ÆS)P


muPython Œ^ óä (setq (cons (setq (cons

auto-mode-alist ’("\\.py$" . python-mode) auto-mode-alist)) interpreter-mode-alist ’("python" . python-mode) interpreter-mode-alist)) (autoload ’python-mode "python-mode" "Python editing mode." t) ;; Š{p wÂŤ (setq font-lock-maximum-decoration t) 4. u SC"3Emacs ÂĽ$1§ M-x locate-library RET python-mode RET ATÂŒ¹Ê python-mode.el§XJĂŠĂ˜ §@oATu load-path ¼´Ă˜´Â?½

( ´œ¥"

§2.1.2 python mode Ă„ A5 SCĂ? Emacs python mode ƒ A5"~XÂľ

§?6python “èĂ’k˜ Ă˜^Æҏ ĂŠĂ?

• gĂ„?n ?" ¡Â‚ §python |^ ?‰Â?Š{ Â˜ĂœŠ§cĂ™´TAB ĂšÂ˜Â‚¡Ăœ žÿ§o ´k˜ #œÙŠ Š{Â†Ă˜"ÂŚ^python mode Ă„ ÂŒÂą;Â?ڍ¯K "Ă?Â? Œ›ŠÂœU gC ä ?§X‘ kĂ’§ Â…§^backspace Ă­Ă˜o‡ ? ˜‚ ž§Â?^U˜eĂ’

" Â…3,˜1ĂžUTAB Â…§Ă’ÂŹgĂ„?n ?§ Â…l5Ă˜ ^TAB iĂŽ5LÂŤÂ ?§Ă‘´^˜‚LÂŤ "‘5 Ă??Ă’´§ĂƒĂ˜^Â&#x;oóä w§ ? ĂĽlĂ‘´Â˜ " • gĊ{\ " ĂŠĂľ61 Ă? ?6ĂŹ A:"'Â…i Ă˜Ă“ÂŠ{( ƒ§^Ă˜Ă“ Ă´ĂšL§ ˜8 ," • ÂŚ^backspace ò ĂžÂ˜? ŠÊ žÿ§gĂ„JÂŤ c ? /Â?´=Â˜ÂŹ ŠÊ (ĂĽ" • èßIM-Python ޚk§S ( §Â?)a§¤ Ÿê§CĂž " • èßPython ĂžkĂŠĂľ ~^܊"

§2.1.3 ~^ĂľUĂž~ 1. C-c ! ½Ü M-x py-shell ÂŒ¹ÊĂ„python )ºÏ" annCharles@tom.com

192Â?, 208Â?

Python ÆS)P


§2.1 ÂŚ^Emacs ?6Python §S 2. C-c C-c ½Ü M-x py-execute-buffer ÂŒÂą$1 3?6 python §S"XJĂŠĂ„ python )ºÏ§@oĂ’ÂŹ3Python )ºÏ¼Â‰1§Ă’”˜‡˜‡¡-Ă‘\Ă™ÂĽÂ˜ " 3. C-c |

½Ü M-x py-execute-region

ÂŒÂą$1region ÂĽ §S"region ´Emacs ÂĽ ˜‡ ĂŠĂ? Vg§ĂšĂ€JÂŤÂ?a q"C-@ ½ÜC-<SPC> ÂŒ¹½Ă‚˜‡region mĂž§region (—Ò´ c1I  Â˜"ڇ¡-ÂŒÂąrregion ÂĽ ĂœŠux‰)ºÏ‰1"XJĂŠĂ„ python )ºÏ§ @oĂ’ÂŹ3Python )ºÏ¼Â‰1§Ă’”˜‡˜‡¡-Ă‘\Ă™ÂĽÂ˜ " 4. C-c RET

½Ü M-x py-execute-import-or-reload

ڇ¡-3mu ÂŹ L§¼AOk^§ÂŒÂąr 3?6 ŠÂ‡ÂŠÂ?˜‡module § \ Python )ºÏ¼"mu ÂŹ žÿ§²~‡rڇ ÂŹimport ½Üreload "k

ڇþU§@omu6§Ă’´§?U §C-c RET §$1ÿà “è§UY?U ÂŹ"Ăš ŒŒJp mu„Ă?"ڇ¡-ĂšC-c C-c ƒ'§k߇`:" (a) ¤k ŸêĂšCĂž ½Ă‚Ă‘´3 ÂŹSĂœ§ Ă˜´)ºÏ¼ Ă›CĂž" (b) Python NĂ ĂŹÂŒÂą ĂŠAŠÂ‡ 1꧴uÂ†Ă˜½ " 5. C-c C-s

½Ü M-x py-execute-string

ÂŹ3minibuffer žŒ^rĂ‘\Â˜ĂŁpython “è§, $1ÂŚ"Ăš3NĂ Â˜Â‡ Ÿê žÿ§ÊkÂ?Ă?"\ÂŒÂąĂ‘\Ÿê œ¥§$1ڇŸê"½Ü \ĂŠ,‡ Ÿê ^{Ă˜ Â’½§½ÜÊ,Š{Ă˜ Â’½ žÿ§Â?ÂŒĂŠÂ?B $1{Ăź Â˜ĂŠ{ “è"½Ü wÂ?Ă?Â?´Êk^ §ÂŒÂą$1help(somefunc) ÂŒÂą wÂ?Ă?§½Ü $1type(somevar) wa.§½Üdir(obj) wʖ ¤kĂĄ5" 6. C-c C-#

½Ü M-x comment-region

ÂŒÂąrregion ĂœŠ5ÂşK" M-x uncomment-region ÂŒÂąrregion ĂœŠ 5ÂşK ĂœŠ§ K5Âş"ÚÊNà §SĂŠkÂ?Ă?" 7. C-c C-k ½Ü M-x py-mark-block ÂŒÂąr1I ÂĄ ˜|“菧IPÂ?˜‡region §1IÂŹÂŁĂ„ Â“è mĂž"ÂŒ Âą^C-x C-x 5u region mÞÚ(—" 8. C-M-a ½Ü M-x py-beginning-of-def-or-class annCharles@tom.com

193Â?, 208Â?

Python ÆS)P


muPython ÂŚ^ óä C-M-e ½Ü M-x py-end-of-def-or-class Š O L ÂŤ ÂŁ Ă„ 1 I ˜ ‡def ½class ÂŹ m Ăž ½ Ăś ( — " ÂŒ Âą ÂŚ ^ ĂŤ ĂŞ " ~ X: C-u 1 C-M-a LÂŤÂŁĂ„1I Þß? def ½class ÂŹ mÞڇ¡-A 3Emacs ¤ k ?§ ª¼üŠ^" 9. C-M-h ½Ü M-x py-mark-def-or-class LÂŤr˜‡def ½Üclass Šʏ§IPÂ?˜‡region "ÂŒÂą^C-x C-x 5u region mÞÚ(—"Ă“ ÂŒ¹Œ^ĂŤĂŞ"ڇ¡-A 3Emacs ¤k ?§ ª¼üŠ ^" 10. C-c > ½Ü C-c C-r ½Ü C-c < ½Ü C-c C-l ½Ü

M-x py-shift-region-right M-x py-shift-region-left

ŠOLÂŤrregion •†£Ä§ĂšÂ•mÂŁĂ„§^5UCÂ“è  ?" 11. C-M-j ½Ü M-x indent-new-comment-line 3? Ăľ1 5Âş žÿ›Šk^§LÂŤmŠÂ˜Â‡#1§gĂ„\Ăž5ºÎÒÚ (  ?" 12. C-x $ ½Ü M-x set-selective-display LÂŤÂ?wÂŤÂ˜Â‡ ÂŹÂĽ ¤kaĂšŸê œ¥§ ÛþaĂšŸê ĂŒN§Ú ĂŠ^ w ˜‡ ¼“è Ă“+"ڇ¡-´ÂŒÂą ÉÍê §~X: C-u C-x $ LÂŤĂ› þ§C-x $ LÂŤwÂŤaĂšŸê ĂŒN" 5ڇþUĂ˜´Ú‡¿g§ 5 Âżg§Â?wÂŤÂ ?Š uÂ?½Íê 1"~ XC-u 4 C-x $ XJ˜1 mĂžšk Â˜Â‚ĂŞ u4 §@oĂ’wŒ§Ă„KĂ’Ă˜w §C-x $ LÂŤw¤k 1"TĂ?§python ÂŚ^ ?5LŠ{( §¤¹^ˆ‡ ĂľUÂŒÂą w “è ( " š~ Ă?^! cĂ™´\ §SĂŠÂŒ žÿ§iruĂ™m§Â‘qsĂŒ&Ăš"

§2.2 ٌ?6ĂŹ ÂŒÂą3eÂĄ ÂŒ§w NĂľ ?6ϧXJEmacs Ă˜¡Ăœ\§Ă’Ă€J˜‡¡Ăœ\ ?6ĂŹ" http://www.python.org/cgi-bin/moinmoin/PythonEditors ´§¡r Ă­ ÂŚ^Emacs " JĂ˝ Ă˜Â†" annCharles@tom.com

194Â?, 208Â?

Python ÆS)P


§2.3 NÁ§S

§2.3 NÁ§S NÁ§S Äípdb §¦´python f NÁ ¬"aqGDB §©i.¡§Ø ´éÐ^" ´¦´ . e§kÙ§.¡ Ð §S|^pdb 5NÁ§S"ØLw epdb Ï kék^ "

§2.3.1 ¦^DDD Úpydb NÁpython §S DDD ´ Ͷ ã/.¡ NÁ§S §¦¦^. ´GDB "

NÁóä§;. Ò

ÚDDD ܧpydb ´ pdb U? " Uìe¡ Ú½ ±SCpydb Ú¦^DDD " 1. SCDDD §XJ\ Unix ½öLinux mu C é {§AT®²CÐ DDD "XJvk§ wDDD SCÃþ" 2. e1pydb "·´l http://ftp.debian.org/debian/pool/main/p/pydb/pydb_1.01.orig.tar.gz e1 "XJù ó } {§ \Ué Ð / e1" 3. pydb.py $PATH ¥ 8¹" Ò´`§Shell ±é ¿ $1ù ·-" ~X: $cp pydb.py /usr/bin/pydb 5¿ U¶i§ K.py *ж¡" 4. pydbsupt.py Úpydbcmd.py § 8¹§( import ·- ±é ¦ " ´ $cp pydbsupt.py pydbcmd.py /usr/local/lib/python/ 5. $1 $ddd --pydb Ò ± mã/.¡ " ±ÀJEdit/Preference.../Source èü§r“Refer to Program Source” ¤ “by Full Path Name”§ ± U ? Ú´Äw«1Ò " 6. ÀJFile/Open èü§ m\ §S§Ò ±NÁ " Ï ´ã/.¡§äN NÁ {§¹¢ ¬ Ò¬ " annCharles@tom.com

195 , 208

Python ÆS)P


n Python ~^ ÂŹ

1nĂ™

Python ~ ^ ÂŹ ÂŹ Â?Ă˜Â”Ă˜%Šó@o­½§ÂŒUÂŹC§Ă’”g,Šó Š{´' ­½ § ´ Ă‘5 ŠĂ™(¢Z O " ´k˜ ~^ ´' ­½ "XJĂšp0 Ăš¢S ‡ Ă˜Â˜Â—§Â„´I‡ w # ĂƒĂž "

§3.1 S˜ ÂŹ S˜ ´Ă˜^import Ă’ÂŒÂąÂ† ÂŚ^ "§škĂŠĂľk^ Ÿê" ĂžXe§äN ÂŒÂą ĂƒÞ§½Üprint obj.__doc__ wÂ?Ă?"

§3.1.1 ~^Ÿê ~^ S˜Ÿê3L3.1-1ÂĽ" ~X: >>> help(dir) Help on built-in function dir: dir(...) dir([object]) -> list of strings Return an alphabetized list of names comprising (some of) the attributes of the given object, and of attributes reachable from it: No argument: the names in the current scope. Module object: the module attributes. Type or class object: its attributes, and recursively the annCharles@tom.com

196Â?, 208Â?

Python ÆS)P


§3.1 S˜ ÂŹ help(obj)

3‚Â?Ă?§obj ÂŒ¹´ ?Ă›a."

callable(obj)

w w ˜ ‡obj´ Ă˜ ´ ÂŒ Âą ” Âź ĂŞ ˜ N ^ ÂŚ"

repr(obj)

obj LÂŤiĂŽG§ÂŒÂą|^ڇiĂŽ G^eval Ÿê­ïTʖ ˜‡€ str´Â˜Â‡iĂŽG§LÂŤĂœ{ python Lˆ ÂŞ"ÂˆÂŁĂšÂ‡LÂˆÂŞ

eval(str) dir(obj) hasattr(obj§name) getattr(obj§name) setattr(obj§name§value) delattr(obj§name) vars(obj) locals() globals() type(obj) isinstance(obj§cls) issubclass(subcls§supcls)

wobj name space ÂĽÂŒÂ„ name " w ˜ w ˜ ‡obj name space ÂĽ ´ Ă„ kname ˜‡obj name space ÂĽ ˜‡name" Â? ˜ ‡obj name space ÂĽ name Â? •valueڇobject lobj name space ÂĽĂ­Ă˜Â˜Â‡ name ˆ ÂŁ ˜ ‡object name space" ^dictionary LÂŤ ÂˆÂŁÂ˜Â‡Ă›Ăœname space§^dictionary L ÂŤ ÂˆÂŁÂ˜Â‡ Ă›name space§^dictionary L ÂŤ w˜‡obj a. wwobj´Ă˜´cls instance wwsubcls ´Ă˜´supcls fa

L 3.1-1: Python ­^S˜Ÿê

attributes of its bases. Otherwise: its attributes, its class’s attributes, and recursively the attributes of its class’s base classes. >>> callable(dir) #ÂŒN^ 1 >>> a=1 >>> callable(a) #Ă˜ÂŒN^ 0 >>> a=dir #Ÿê aliase Â?´ÂŒN^ >>> callable(a) 1 annCharles@tom.com

197Â?, 208Â?

Python ÆS)P


n Python ~^ ÂŹ >>> a(" ") #Ăšdir(" ")˜ " [’__add__’, ’__class__’, ’__contains__’, ’__delattr__’, ’__doc__’, ’__eq__’, ’__ge__’, ’__getattribute__’, ’__getitem__’, ’__getslice__’, ’__gt__’, ’__hash__’, ’__init__’, ’__le__’, ’__len__’, ’__lt__’, ’__mul__’, ’__ne__’, ’__new__’, ’__reduce__’, ’__repr__’, ’__rmul__’, ’__setattr__’, ’__str__’, ’capitalize’, ’center’, ’count’, ’decode’, ’encode’, ’endswith’, ’expandtabs’, ’find’, ’index’, ’isalnum’, ’isalpha’, ’isdigit’, ’islower’, ’isspace’, ’istitle’, ’isupper’, ’join’, ’ljust’, ’lower’, ’lstrip’, ’replace’, ’rfind’, ’rindex’, ’rjust’, ’rstrip’, ’split’, ’splitlines’, ’startswith’, ’strip’, ’swapcase’, ’title’, ’translate’, ’upper’] >>> repr({"one":1,"two":2}) # repr ^u iĂŽG§^5LÂŤ ʖ "{’two’: 2, ’one’: 1}" >>> a=[1,2] >>> eval(repr(a)) # eval Ăš repr ÂŒÂą Â˜Â‡ĂŠÂ– € " [1, 2] >>> a [1, 2] >>> hasattr(a,"append") 1 >>> getattr(a,"append")(3) >>> getattr(a,"append")(4) >>> a [1, 2, 3, 4] >>> type(a) <type ’list’>

§3.1.2 a.=†Ÿê ~^a.=†ŸêXL3.1-2 Ăž~: >>> chr(65) ’A’ >>> [ord(k) for k in "ABC"] [65, 66, 67] >>> oct(65) , oct(65000),oct(650000000) (’0101’, ’0176750’, ’04657433200’) annCharles@tom.com

198Â?, 208Â?

Python ÆS)P


§3.1 S˜ ÂŹ chr(i) ord(i) oct(x) hex(x) str(obj) list(seq) tuple(seq) dict()§dict(list) int (x) long(x) float(x) complex(x) max(... min(...)

r˜‡ASCII ꊧC¤iĂŽ r˜‡iĂŽ½ÜunicodeiĂŽ§C¤ASCII êŠ r ĂŞx C¤l?›LÂŤ iĂŽG r ĂŞx C¤Â›8?›LÂŤ iĂŽG obj iĂŽGÂŁĂŁ r˜‡sequence =†¤Â˜Â‡list r˜‡sequence =†¤Â˜Â‡tuple =†¤Â˜Â‡dictionary =†¤Â˜Â‡integer =†¤Â˜Â‡long integer =†¤Â˜Â‡2:ĂŞ =†¤EĂŞ ÂŚÂ ÂŒÂŠ Œ Š L 3.1-2: a.=†Ÿê

>>> hex(65) , hex(65000),hex(650000000) (’0x41’, ’0xfde8’, ’0x26be3680’) >>> str(10),str([1,2]),str({"one":1}) (’10’, ’[1, 2]’, "{’one’: 1}") >>> list("abc"),list((1,2,3)) ([’a’, ’b’, ’c’], [1, 2, 3]) >>> tuple("abc"),tuple([1,2,3]) ((’a’, ’b’, ’c’), (1, 2, 3)) >>> dict(),dict([("one",1),("two",2)]) ({}, {’two’: 2, ’one’: 1}) >>> dict([ ( str(x), x) for x in [1,2] ]) {’1’: 1, ’2’: 2} >>> int(1),int("1"),int(1.4),int(1.6) (1, 1, 1, 1) >>> int("1.2") #Ă˜1, 1.2 wĂĽ5Ă˜Â” ĂŞ Traceback (most recent call last): File "<stdin>", line 1, in ? ValueError: invalid literal for int(): 1.2 >>> long(1),long("1"),long(1.4),long(1.6) (1L, 1L, 1L, 1L) annCharles@tom.com

199Â?, 208Â?

Python ÆS)P


n Python ~^ ÂŹ >>> float(1),float("1.2"),float("1e-4") (1.0, 1.2, 0.0001) >>> min(1,2,3,4,5) 1 >>> min([1,2,3,4,5]) 1 >>> max([1,2,3,4,5]) 5 >>> max(1,2,3,4,5) 5

§3.1.3 ^u‰1§S S˜Ÿê \ ÂŹ import§ \˜‡module" ‰1“è exec code [ in globaldict[,localdict]]" >>> exec "a=1" #3 c namespace މ1“è. >>> a 1 >>> mynamespace={} #MĂŻÂ˜Â‡Â˜ dictionary,^u ;namespace >>> exec "a=1" in mynamespace #3 mynamespace މ1“è. >>> print mynamespace.keys() # w(J [’__builtins__’, ’a’] #Ăš\߇name >>> type(mynamespace["__builtins__"]) <type ’dict’> #e˜‡Â?ÂŻ< ~f >>> class A: #˜‡˜ class ... pass ... >>> exec "a=1" in vars(A) #O\Â˜Â‡ĂĄ5 >>> A.a #¤þ 1 >>> exec "def abc(self): print ’ok’ " in vars(A) # „UO\˜‡ methord >>> dir(A) #5Âż,k abc

annCharles@tom.com

1100Â?, 208Â?

Python ÆS)P


§3.1 S˜ ÂŹ [’__builtins__’, ’__doc__’, ’__module__’, ’a’, ’abc’] >>> x=A() >>> x.abc() #¤þ ok >>> ڍÂ?ª´Ê(šĂšrÂŒ § ´ŒÊJÂ€Ăˆ¤Â?C++ ½ÜJava Šó"Ă˜Âš§\( ½^Python ŠÂ?§Smu ĂŒNŠó§ Â…ĂŠPython 5UĂŠk&%§Ă˜ÂŽ^Ă™§ÂŠĂł XC++ ­ , ĂľU ÂŹ"Â?Â&#x;oÂŹ^C++ ­ § Ă˜´Â† ^C++ Q? Ăš 9 ˜ ‡^‡ó§ ‘K"{Ăź/`§^C++ ÂŒU †§ºx ÂŒ"Python Â?ÂŒU †§ ´ Âşx "C++ Ăž5Ă’°H[Â?§(J ÂŠÂŹÂŒUĂ˜´^r‡ "Python ´Âƒ£§^rÂŒ ÂąkwÂ˜Â‡Ă“+§, 2°H[T§^C++ ­ , ÂŹ" ˜´ĂŽĂ™ .§ĂšĂĽÂşx \O§Â˜´S“ .§Ă…Ăš[z§ºÂ˜Âşx" ^C++­ ´Ăƒã§Ă˜´8 §8 ´ávÂ?r IÂŚ"XJÂŒ¹áv^r IΤĂ’Ă˜ ^­ " Ă’ÂŽĂ˜Uáv^r IΤÂ?Ă˜Â‡:X?U§kÿÞ§ww5U´œ3=p§k ˜¼§O\Ă&#x;§¤ Êþüí§5UvkUCĂľ § Ă˜Ă˜v ó§python kprofile module ^uOÂŽpython §SÂĽzã“è 5U"ĂŠ “´œâ€?§(@“´œâ€?§, `z" ?ĂˆÂ“è compile§XJÂ˜ĂŁÂ“è²~‡Œ^§@ok?Ăˆ§2$1ÂŹÂ?ÂŻ" >>> c=compile("print ’hello’","abc","single") >>> exec c hello >>> c=compile("raise 1 ","abc","single") >>> exec c Traceback (most recent call last): File "<stdin>", line 1, in ? File "abc", line 1, in ? # 5¿ŠÂ‡ϫ abc TypeError: exceptions must be strings, classes, or instances, not int compilekn‡ꐤ1˜‡“èiĂŽG"´ÊA Python §S ŠÂ‡œ¥§Œ^u3 ‰1Â“è§ )É~ žÿ§Â‹<ц&E"1n‡Íê´â€œsingleâ€?§â€œexecâ€? “evalâ€?nĂśÂƒ ˜§Ú Ăťu“è´å=‹<(J Šʧ„´Â˜|Šʧ„´Â˜Â‡LÂˆÂŞ"eÂĄ ~f' ?ĂˆĂšĂ˜?Ăˆ 5U O" >>> code="print ’Hello World’" annCharles@tom.com

1101Â?, 208Â?

Python ÆS)P


n Python ~^ ÂŹ >>> c=compile(code,"abc","exec") >>> profile.run("for i in range(10000): exec c") 10002 function calls in 0.250 CPU seconds Ordered by: standard name ncalls 1 10000 1

tottime 0.090 0.160 0.000

0

0.000

percall 0.090 0.000 0.000

cumtime 0.250 0.160 0.250 0.000

percall 0.250 0.000 0.250

filename:lineno(function) <string>:1(?) abc:1(?) profile:0(for i in range(10000): exec c) profile:0(profiler)

>>> profile.run("for i in range(10000): exec code") 10002 function calls (2 primitive calls) in 0.720 CPU seconds Ordered by: standard name ncalls tottime percall cumtime percall filename:lineno(function) 10001/1 0.720 0.000 0.720 0.720 <string>:1(?) 1 0.000 0.000 0.720 0.720 profile:0(for i in range(10000): exec code) 0 0.000 0.000 profile:0(profiler) ÂŒÂąw §Â˜Â‡´0.250‡CPU seconds§Â˜Â‡´0.720 CPU second"ÂŒÂąJp5UÂŒ 3 " OÂŽLÂˆÂŞ eval(str) ^uÂˆÂŁÂ˜Â‡LÂˆÂŞ"5Âż LÂˆÂŞ Š{ڊÊ Š{´Ă˜Ă“ " >>> a=2 >>> eval("a==1") 0 >>> eval("a=1") Traceback (most recent call last): File "<stdin>", line 1, in ? File "<string>", line 1 a=1 ^ annCharles@tom.com

1102Â?, 208Â?

Python ÆS)P


§3.2 Ú܊XĂšÂƒ' N^ SyntaxError: invalid syntax

§3.2 Ú܊XĂšÂƒ' N^ ĂšXĂšÂƒ' &EĂ‘3sys ¼§^import sysÂŚ^" ~X§ ¡-1ĂŤĂŞ(command line arguments)"sys.argv´Â˜Â‡list§Â?š¤k ¡-1ĂŤĂŞ" IOĂ‘\Ă‘Ă‘"sys.stdout§sys.stdin§sys.stderr ŠOLÂŤIOĂ‘\Ă‘Ă‘§ Â†Ă˜Ă‘Ă‘ ŠÂ‡ĂŠÂ–" òĂ‘§S"sys.exit(exit_code) X Ăš ÂĽ modules§sys.modules´ ˜ ‡dictionary § L ÂŤ X Ăš ÂĽ ¤ k ÂŒ ^ module §~Xsys.modules["os"] LÂŤmodule os§Â?Ă’´`Œ‚Â?Â•Ă“Â˜Â‡ĂŠÂ–" $1 ܊Xڂ¸sys.platform sys.path ´Â˜Â‡list§Â?²¤k ĂŠmodule §package ´" Ú܊XĂšÂƒ' N^Ú܊os ¼§^import osÂŚ^" os.environ

os.chdir(dir) os.cwd() os.getegid() os.getgid() os.getuid() os.geteuid() os.setegid() os.setgid() os.setuid() os.seteuid() os.getgroups() os.getlogin() os.getenv os.putenv os.umask

˜ ‡dictionary§ Â? š ‚ ¸ C Ăž N ' X"os.environ["HOME"] ÂŒÂą ‚¸CĂžHOME Š" UC c8š c8š k |id |id ^rid k ^rid ˜k |id ˜|id ˜^rid ˜k ^rid ^r|ϴ L ^r šœ¥ ‚¸CĂž ˜‚¸CĂž ˜umask L 3.2-3: XĂšN^Ăž~

Ăľ §L3.2-3 == Ă‘Â˜ ĂœŠ"Â?‡UÂŽ XĂšN^§3pythonÂĽĂ‘UĂŠ " annCharles@tom.com

1103Â?, 208Â?

Python ÆS)P


n Python ~^ ÂŹ eÂĄkA‡~f" ˜‡{Ăź shell |^os.system() ? ˜‡{Ăź shell" #!/usr/bin/python import os,sys cmd=sys.stdin.readline() while cmd: os.system(cmd) cmd=sys.stdin.readline() os.system(cmd)|^XĂšN^§$1lIOĂ‘\Ă–5 ¡-" Ă„ ŠÂ‡ĂśÂŠĂľU |^os ÂĽ Ă„ ŠÂ‡ĂśÂŠĂľU"k:aqshell§ ,Ă‘\Ă˜ {Ăś" >>> os.mkdir(’/tmp/xx’) #MĂŻ8š >>> os.system("echo ’hello’ > /tmp/xx/a.txt") 0 >>> os.listdir(’/tmp/xx’) >>> os.listdir(’/tmp/xx’) [’a.txt’] >>> os.rename(’/tmp/xx/a.txt’,’/tmp/xx/b.txt’) >>> os.listdir(’/tmp/xx’) [’b.txt’] >>> os.remove(’/tmp/xx/b.txt’) >>> os.listdir(’/tmp/xx’) [] >>> os.rmdir(’/tmp/xx’) >>> os.listdir(’/tmp/xx’) #¤þíĂ˜ 8š Traceback (most recent call last): File "<stdin>", line 1, in ? OSError: [Errno 2] No such file or directory: ’/tmp/xx’ „kchown§chmod§unlink§symlink§link "Ă™GUnix §ATÂ?Ă™GĂš ܊" os ¼„kÊþŸê§¯¢Þ§Â?‡´POSIX IOŸê¹93ÂŒþêUnix ² 2Â? ÂŚ^ Ÿê3Python Unix ‡ pÂĄĂ‘´|Âą "Ăš Ă‘´Â„ĂŒPOSIX .~"k Ă– ‰5Advanced Programming In Unix Environments 6ĂŠĂ? 0 Unix e ?§" annCharles@tom.com

1104Â?, 208Â?

Python ÆS)P


§3.2 Ú܊XĂšÂƒ' N^ Â?)pipe§dup§open ܊+ §ŠÂ‡ÂŁĂŁĂŽ§?§§ªà §?Ă–§^r§^r| " ^os.path ? ² Ăƒ' §S ^os.path ? Ă• ĂĄ u ² § S " ¡ ‚ Windows(DOS)§MAC ĂšUnix ' u Š ‡ Âś ÂĄ § 8 š Âś ÂĄ § ´ Âť Âś ÂĄ ^ { ´ Ă˜ Ă“ " ˜ ‡ { Ăź ~ f ´ §DOSe ¡ ‚ ^C:\temp\a.txt LÂŤÂ˜Â‡ŠÂ‡Unix e´/tmp/a.txt"eÂĄ ~fÂŒÂąw ˜ ^{: >>> os.getcwd() ’/home/Charles’ >>> os.path.split(os.getcwd()) (’/home’, ’Charles’) #^uŠm˜‡8šœ¥¼ 8šĂœŠĂšŠÂ‡ϴĂœŠ. >>> print os.path.join(os.getcwd(),os.pardir,’a’,"a.doc") /home/Charles/../backup/a.doc #Ăšsplitƒ‡,Ăœ¤´œ¥. #os.pardir LÂŤ c² eLÂŤĂžÂ˜?8š iĂŽ .. >>> print os.path.exists(os.getcwd()) 1 # äŠÂ‡´Ă„ 3. >>> os.path.expanduser(’~/dir’) ’/home/Charles/dir’ #r ~ *Ă?¤^rŠ8š. #3 Windows eÂŒU´ H:\Charles\dir >>> os.path.expandvars(’$TMP’) ’/tmp’ #*Ă?‚¸CĂž,Windows eÂŒU´ c:\temp >>> os.path.isfile(os.getcwd()) 0 #´ŠÂ‡œíº0, Ă˜´ >>> os.path.isfile(os.path.expanduser("~/tmp/a.c")) 1 # ¡ 8šeÂĄk /home/Charles/tmp/a.cڇŠÂ‡ >>> os.path.isdir(os.getcwd()) 1 #´8šíº 1, ´ >>> os.path.islink(os.getcwd()) 0 annCharles@tom.com

1105Â?, 208Â?

Python ÆS)P


n Python ~^ ÂŹ #´ĂŽĂ’ĂŤ Ă­ÂşWindows eÂŒUĂ˜U^ڇŸê >>> os.path.ismount(os.getcwd()) 1 #´ŠÂ‡XĂšSC:Ă­ÂşWindows eÂŒUĂ˜U^ڇŸê >>> os.path.samefile(os.getcwd(),’/home/Charles’) 1 #ww߇ŠÂ‡œ¥´Ă˜´Â? Ă“Â˜Â‡ŠÂ‡. >>> def test_find(filename,dirname,names): ... if filename in names: ... print os.path.join(dirname,filename) ... >>> os.path.walk(’/home/Charles’,test_find,"a.c") /home/Charles/tmp/a.c  Â˜Â‡~fĂŠkÂżg§os.path.walk(p,func,arg) 1˜‡Íê´Â˜Â‡8šœi§1 ‡Íê´Â˜Â‡Ÿê Âśi§1n‡Íê‘B´Â&#x;o"os.path.walk ÂŹrH{p e ¤k f8š§Â?)p§Êuz˜‡8š§Ă‘ÂŹN^func§func(arg,dirname,names) 1˜‡ ĂŤĂŞĂ’´§walk  Â˜Â‡ĂŤĂŞarg§dirname´Â–ÂŻ 8šœ¥"names ´Â˜Â‡list§Â? šdirname8še ¤kSN"Ăš Þ¥@ 41§S Âżg´§3,‡8š¼§ĂšŒ¤ k f8š¼ ʜ¥´a.c ŠÂ‡½Ü8š"¡´3Unix ‚¸e§Windows eATa q"

§3.2.1 ‹mŠÂ‡ file ʖ´Â˜Â‡Ăšstring§integer§float ˜ SÂ˜ĂŠÂ–a."ÂŚkÂąeÂ?{" f=open("filename","r") filename Â? ½ Š ‡ Âś ÂĄ §â€œrâ€?Â? ^ Â? Ă– Â? ÂŞ ‹ m §â€œwâ€?L ÂŤ Â? ÂŞ §â€œrwâ€?L ÂŤ Ă– Â? ª§â€œrbâ€?LÂŤĂ– ?›Â?ª§â€œwbâ€?LÂŤ ?›Â?ÂŞ"

§3.2.2 Ă– ŠÂ‡ openÂˆÂŁÂ˜Â‡file ʖ§ÂŒÂą^˜eÂ?{Ă– ˜‡ŠÂ‡" >>> f=open("/tmp/x.txt","w") >>> f.write("a") >>> f.close() >>> f=open("/tmp/x.txt","r") >>> f.read() ’a’ >>> f.read() annCharles@tom.com

1106Â?, 208Â?

Python ÆS)P


§3.3 regular expression ’’ Úã“èk‹m˜‡ŠÂ‡§, ˜‡iĂŽ§, '4§2^Ă–Â?ª‹m§Ă–Ă‘5 ff ? iĂŽ"f.read(size)LÂŤlŠÂ‡ÂĽĂ– size ‡iĂŽ§XJ Ă‘size @oòr¤ k SNĂ–Ă‘5"XJ ŠÂ‡ (—§f.read(size) ÂŹÂˆÂŁÂ˜Â‡Â˜ iĂŽG"5Âż ˜ iĂŽGLÂŤĂœ6b§ÂŒÂą^eÂĄ Â?ÂŞÂ˜Â‡Â˜Â‡ iĂŽĂ– " f.open("/tmp/x.txt","r") c=f.read(1) while c: print c c=f.read(1) f.readline() Ă– ˜1§¡^u1܊"XJ ŠÂ‡(—§Ă’ÂˆÂŁÂ˜ iĂŽG" f.readlines() Ă– ŠÂ‡ ¤kSN§ÂˆÂŁÂ˜Â‡list §list ÂĽ z˜‡ ƒLÂŤÂ˜1§ Â?šâ€œ\nâ€?" f.write(str)r˜‡iĂŽG \ ŠÂ‡ÂĽ " f.tell() ÂˆÂŁ cŠÂ‡Ă–  Â˜" f.seek(off,where) ^5½ ŠÂ‡Ă–  Â˜"where= 0 LÂŤlmÂŽü§1LÂŤl c Â˜ÂŽü§2LÂŤl(—Žü"offLÂŤÂŁĂ„  £Þ§ ꕊ‡(—£Ä§KĂŞLÂŤ •ŠÂ‡mÞ£Ä"5Âż sys ÂĽ sys.stdout§sys.stderr §sys.stdin ´n‡›Šk^ ŠÂ‡ĂŠÂ–" >>> import sys >>> a=sys.stdin.readline() Hello #Ă‘\˜‡iĂŽG >>> sys.stdout.write(a) Hello #Ă‘Ă‘ >>> ÚÖ܊ÊA ܊´writeline§write§writelines"

§3.2.3 '4ŠÂ‡ Â?,Python ÂŹgĂ„rvk'4 ŠÂ‡Ă‘'K§ ´²w Â?²'4ŠÂ‡o´Â˜Â‡Ă?5 ¿§^ Ă€ĂœÂ‡Â˜ÂŹ  § ä‡P Ă‚Â? à §¯ Œ‡P M "'M { ߧf.close()(ĂĽ"

§3.3 regular expression regular expression ( KLÂˆÂŞ)§{ÂĄregexp§´?Ăˆ nÂĽ ˜‡Vg§3Unix ­ . ÂĽ Ăƒ ¤ Ă˜ 3 §vi!emacs!sed!awk!perl Ă‘ 2 Â? ÂŚ ^ "python ÂĽ re§ ´ ˜ annCharles@tom.com

1107Â?, 208Â?

Python ÆS)P


n Python ~^ ÂŹ ‡regexp module Ă?LÂŚÂŒÂąÂ”perl ÂĽÂ˜ ÂŚ^regexp"regexp Ă’´Â˜ÂŤLÂŤÂ˜Â‡iĂŽ G8Ăœ(set) Â?{"`,‡iĂŽGĂš,‡regexp š (match¤§¿gĂ’´`ڇiĂŽG ´regexp ¤Lˆ 8ĂœÂĽ ˜‡ ƒ"3Python ¼§match „LÂŤ,‡iĂŽG mĂž ˜ ĂœŠĂš,‡regexp match"

§3.3.1 {Ăź regexp  {Ăź regexp LÂŤkeZiĂŽ|¤§LÂŤiĂŽ " >>> p=re.compile("abc") >>> if p.match("abc") : print "match" ... match >>> Ăš p 0 ˜ ‡ { Ăź ^ { § Ă„ k ‡ ) ¤ ^re.compile("abc") ˜ ‡pattern ( ÂŞ)§pattern ˜‡match Â?{§XJĂš,‡iĂŽGš §Ă’ÂˆÂŁÂ˜Â‡match object§ Ă„KĂ’ÂˆÂŁNone"Ă˜ , AĂ?iĂŽmetacharacter ( iĂŽ) §ÂŒþêiĂŽĂ‘Ăšg š " Ăš AĂ?iĂŽ´ " ^ $ * + ? { [ ] \ | ( )

§3.3.2 iĂŽ8Ăœ ^[]ÂŒÂąLÂŤiĂŽ 8Ăœ"kÂąeAÂŤ^{ • Ă‘iĂŽ§X[abc] Lš a ½Üb ½Üc§½Ü`i1a§b§c Ă‘3[abc]LÂŤ 8ĂœÂĽ"ÂŒþêmetacharacter 3[] ¼” metacharacter AĂ?¿Â§Â?LÂŤ Ăš š "~X: >>> >>> >>> ... ... ... ... ... [.] [^] [$] [*]

a=".^$*+?{\\|()" p = re.compile("["+a+"]") for i in a: if p.match(i): print "[%s] is match"%i else: print "[%s] is not match"%i is is is is

match match match match

annCharles@tom.com

1108Â?, 208Â?

Python ÆS)P


§3.3 regular expression [+] [?] [{] [\] [|] [(] [)]

is is is is is is is

match match match not match match match match

Œ„Œþêmetacharacter 3[]ÂĽĂ‘Ăš š § ´ko‡metacharacter Ă˜Ăš š §@Ă’´â€œ^[]\â€?§ ÂĄÂŹÂ˜Â‡Â˜Â‡`²§^ LÂŤ ‡§ ÂĄ0 §[]XJĂ‘y 3[]¼§Ă’ŠĂ˜Â˜Ă™=p´mĂž=p´(— "\ Š^´^5LÂŤĂƒ{^‹< iĂŽ " • XĂ›3[]ÂĽÂ?š[] §LÂŤĂšâ€œ[â€? ½Ü“]â€? š ? >>> p=re.compile("[\]\[]") >>> p.match("]") <_sre.SRE_Match object at 0x815de60> >>> p.match("]") <_sre.SRE_Match object at 0x81585e8> >>> p.match("[") <_sre.SRE_Match object at 0x8158330> ^\[ Ăš\] LÂŤ • ^ Ă‘y3[] mĂž§LÂŤ ‡§Ăš[]ÂĽ iĂŽĂ‘Ă˜Âš §vkĂ‘y Қ "[^abc] Lš Ă˜ a§b§cƒ ¤kiĂŽ"^ Ă‘y3[] ÂĽm {§Ă’vkڇ¿g § LÂŤ^iĂŽ "wÞ¥ ~f§^vkĂ‘y3mĂž§Ă’Ăšg š " • ÂŒÂą^-LÂŤÂ‰ÂŒ"[a-zA-Z]š ?Ă›Â˜Â‡=Ši1"[0-9]š ?Ă›Â˜Â‡ĂŞi" • \ 3[] ÂĽ Ă™ŒŠ^" \d \D \s \S \w \W \t \x20

[0-9] [^0-9] [ \t\n\r\f\v] [^ \t\n\r\f\v] [a-zA-Z0-9_] [^a-zA-Z0-9_] LÂŤĂštab š §Ă™ÂŚ Ă‘ĂšiĂŽG LÂŤ{˜— LÚ›8?›ascii 0x20 š

k \ §ÂŒÂą3[] ÂĽLÂŤ?Ă›iĂŽ"5¿§ßĂ• ˜‡“.â€? XJvkĂ‘y[]¼§LÂŤ Ă˜ †1\n Âą š ?Ă›iĂŽ"aq[^\n]" annCharles@tom.com

1109Â?, 208Â?

Python ÆS)P


n Python ~^ ÂŹ

§3.3.3 ­E ÂŒÂą^˜eÂ?{LÂŤÂ˜Â‡regexp ­E" • {m,n} L ÂŤ Ă‘ ym ‡ Âą Ăž(Â? šm‡)§n‡ Âą e(Â? šn‡)" Xab{1,3}c Ă’ ÂŹ Ăšabc§abbc§abbbc š § ´Ă˜ÂŹĂšac§abbbbc š "m´e.§n´Þ."mÂŒ ¹ŽÑ§LÂŤe.´0§nÂŒÂąÂŽĂ‘§LÂŤĂž.´Ăƒ ÂŒ" • * LÂŤ{,}§vkĂ‘y(0g)§­EĂ‘y1g¹Þ" • + LÂŤ{1,}§­EĂ‘y1g¹Þ • ? LÂŤ{0,1}§­EĂ‘y0g½Ü1g"  ÂŒÂš Ăš Âš ÂŻK"Â?Â&#x;oÂŹkڇ¯KÂşweÂĄ ~f"[ab]* Ăšababab ?1 š §@o´Ăša š „´Ăšababab š QÂşXJĂša š § ‰ Âš §Ăšababab š § ‰ ÂŒÂš "python ÂĽĂ‘´ ÂŒÂš " >>> re.compile("a*").match(’aaaa’).end() 4 >>> re.compile("a*?").match(’aaaa’).end() 0 match object endÂŒ Âą š  Â˜ ‡ i ĂŽ  Â˜ " X J ‡  Âš § @ o Ă’ 3*§+§?§{m,n} ÂĄ\˜‡?§C¤*?§+?§??§{m,n}?L š "

§3.3.4 ÂŚ^ ŠiĂŽG ¡ ‚ § i ĂŽ G L ÂŤ Â? { ÂĽ ^\\ L ÂŤ i ĂŽ\§ 3regexp ÂĽ ÂŒ Ăž ÂŚ ^\§ ¤ Âą 3regexpÂĽ Ă‘ y ÂŒ Ăž\\Ăš K Â? ÂŒ Ă– 5 § ‡ 3regexp ÂĽ š \ I ‡ Ăš re.compile("\\\\") Ăš Ê̆")ÝÚ‡¯K Â?{´¾3iĂŽGcÂĄ\˜‡r LÂŤraw ‚ª§\ AĂ?Š^Ă’Ă˜Â„ "¤¹3python LÂŤregexpÂ˜Â„Ă‘^\r Â?{"~ X >>> >>> \a >>> >>> \"a >>>

a=r"\a" print a a=r"\"a" print a

§3.3.5 ÂŚ^re ÂŹ ÂŚ^regexp§Ă?~^ÂąeA‡Ú½¾ annCharles@tom.com

1110Â?, 208Â?

Python ÆS)P


§3.3 regular expression • k^re.compile ˜‡RegexObject§LÂŤÂ˜Â‡regexp" • , ^pattern match§search Â?{§ MatchObject" • 2^match object š  Â˜§Âš iĂŽG &E" RegxObject ~^Ÿê: • RE_obj.match(str,[pos[,endpos]])§ X Jstr m Ăž ĂšRE_objš § ˜ ‡MatchObject Ă„KÂˆÂŁNone"5Âż ´lstr mĂžmŠ?1š " >>> re.compile("a").match("abab") <_sre.SRE_Match object at 0x81d43c8> >>> print re.compile("a").match("bbab") None • RE_obj.search(str,[pos[,endpos]])§3strÂĽ|¢1Â˜Â‡ĂšRE_objš ĂœŠ" >>> re.compile("a").search("abab") <_sre.SRE_Match object at 0x81d43c8> >>> print re.compile("a").search("bbab") <_sre.SRE_Match object at 0x8184e18> 5¿Úmatch() Ă˜Ă“"Ă˜7lmÞҚ " • RE_obj.findall(str)§ÂˆÂŁstrÂĽ|¢¤kĂšRE_objš ĂœŠ"ÂˆÂŁÂ˜Â‡tuple§ Ù¼ ƒ´Âš iĂŽG" MatchObject ~^Ÿê • m.start() ˆ£üŠ Â˜§ÊuRE_obj.match()ÂˆÂŁ MatchObject§start()o´ ÂˆÂŁ0 • m.end() ÂˆÂŁ(ĂĽÂ Â˜(Ă˜Â?šT Â˜ iĂŽ)" >>> s="I say:helloworld" >>> m=re.compile("hello").search(s) >>> for i in range(m.start(),m.end()): ... print s[i] ... h e l l o >>> annCharles@tom.com

1111Â?, 208Â?

Python ÆS)P


n Python ~^ ÂŹ • m.span() ÂˆÂŁÂ˜Â‡tuple LÂŤ(m.start(),m.end())" • m.pos()§m.endpos()§m.re()§m.string() § Ăš Š O L ÂŤ ) ¤ Ăš ‡MatchObjectŸê¼ ĂŤĂŞ" RE_obj.match(str,[pos[,endpos]]),RE_obj.search(str,[pos[,endpos]]) ÂĽ pos§endpos§RE_obj§str"Â?Ă’´` m.re().search(m.string(),m.pos(),m.endpos()) ÂŹ m " • m.finditer() ÂŒÂąÂˆÂŁÂ˜Â‡iterator§^5H{¤kĂŠ MatchObject" >>> ... ... (1, (3, (5, (7,

for m in re.compile("[ab]").finditer("tatbxaxb"): print m.span() 2) 4) 6) 8)

§3.3.6 p?regexp Ă˜ cÂĄ0 §Â„kĂŠĂľk^ Lˆregexp Â?ÂŞ" • | LÂŤĂŠĂœĂľÂ‡regexp "XJA ĂšB ´ß‡regexp §@oA|B LÂŤĂšA š ½ÜĂšB š " ´5Âż | OÂŽ`k? $§Good|Bad ÂŹĂšâ€œGoodâ€? ½Ü“Badâ€? š §Ă˜ ÂŹĂšâ€œGoodadâ€? ½Ü“GooBadâ€?š " • ^ LÂŤÂ?š ˜1 mŠ1Ă„"~X“^abcâ€?ÂŹĂšâ€œabcâ€?š § ´Ă˜ÂŹÂš “xabcâ€?§c Ă™´^search žÿ"^ Â?3mĂžâkڍAĂ?¿Â§Ă’´´`§Â?k3mĂž§^â ´metacharacter §Ă„K^ Ă’´Â˜Â‡ĂŠĂ?iĂŽ" • $ LÂŤÂ?š ˜1 (—"Ăš^ aq§Â?k3 Â˜Â‡iĂŽ žÿ§$ âkڍAĂ?Âż g" • \A LÂŤÂ?š iĂŽG mĂž"XJvk3Ăľ1 ÂŞ(MULTILINE) e žÿ§\A Ăš^ ´Â˜Â‡Âżg§ ´3Ăľ1 ÂŞe\A Â?š 1˜1 1Ă„" ^š z˜1 1Ă„" • \Z LÂŤÂ?š iĂŽG (—"XJvk3Ăľ1 ÂŞ(MULTILINE) e žÿ§\Z Ăš$ ´Â˜Â‡Âżg§ ´3Ăľ1 ÂŞe\Z Â?š  Â˜1 1—" ^š z˜1 1—" • \b Â?š c >.§3NJ¼§c >.´ÊJ.½ § ´3=Š¼I:ĂŽĂ’§Â˜ ‚ Ă‘ÂŒÂąLÂŤÂ˜Â‡Ăźc >.§Ă™ÂŚÂŠĂłÂ?kaq§äNXĂ›.½§dlocale Ăť ½"~X\binfo\b Â?š “infoâ€? Ă˜ÂŹÂš “informationâ€?" ´Â‡5ÂżeÂĄ ~ f" annCharles@tom.com

1112Â?, 208Â?

Python ÆS)P


§3.3 regular expression >>> print re.compile(r"\binfo\b").match("info ") <_sre.SRE_Match object at 0x817aa98> >>> print re.compile("\binfo\b").match("info ") None >>> print re.compile("\binfo\b").match("\binfo\b <_sre.SRE_Match object at 0x8174948>

#ÂŚ^ raw ‚ª #\b LÂŤĂźc>. #vkÂŚ^ raw ‚ª #\b Lò‚ÎÒ ")

5ÂżVÚÒcÂĄ r"3vk´^raw ‚ª žÿ§\bLò‚ÎÒ§0x8§Œ^raw ‚ª žÿ\bLÂŤĂźc >." • \B Lš šßc>." ¹Þ¤k metacharacter ÂżĂ˜ĂšĂ˝ iΚ §Â?´Â˜ÂŤ^‡u §Ă˜ÂŹÂŚ^š ĂœŠO\ Ă?"~X: ^abc š “abcâ€?§ ´Âš Ă?„´3"1

§3.3.7 Š|(Group) Ă?~Âœš§\Ă˝ Ž‡ Â?´Âš iĂŽGÂĽ Â˜ĂœŠ§ Ă˜´ Ăœ"regexp ²~^ 5r˜‡iĂŽGŠ)¤AÂ‡ĂœŠ§Ú ~fÊþ§Xemail ¼Š)email header(&Ăž) Ăšemail body ( Š)§email header ÂĽq‡Š)u&<§Ă‚&< §email /ÂŒÂĽq‡Š )^rœ¥§Ăš^rÂ?Âś"~X§\^eÂĄ ‚ª ;˜‡Ă?&š" name: Charles Address: BUPT telephone: 62281234 email: annCharles@tom.com name: Ann Address: BUPT telephone: 62284321 email: CharlesWang@peoplemail.com.cn ^˜1ŠmPš"@҇ Charles §Ann ϴĂœŠ§BUPT /ÂŒĂœŠ "XĂ›) ÝÚ‡¯KQ? Group ! weÂĄ ~f" >>> ... ... ... ... ... 1

x=""" name: Charles Address: BUPT telephone: 62281234 email: annCharles@tom.com

3lex ¼§â€œË† abcâ€? š Ă?'“abcâ€? ÂŒ

annCharles@tom.com

1113Â?, 208Â?

Python ÆS)P


n Python ~^ ÂŹ ... name: Ann ... Address: BUPT ... telephone: 62284321 ... email: CharlesWang@peoplemail.com.cn ... """ >>> p=re.compile( ... r"^name:(.*)\n^Address:(.*)\n^telephone:(.*)\n^email:(.*)\n",re.M) >>> for m in p.finditer(x): ... print "here is your friends list" ... print "%s,%s,%s,%s"%m.groups() ... here is your friends list Charles, BUPT, 62281234, annCharles@tom.com here is your friends list Ann, BUPT, 62284321, CharlesWang@peoplemail.com.cn ڇ~fk:E,§ ´ATvkÂ&#x;oŠ{Â?ÂĄ ÂŻK§þêÂœšÂŒÂą ĂƒĂž)ݯK" 'Â…3p.compile()?§Ă™ÂĽ(.*)ÂĽĂľ ˜‡)Ă’§LÂŤgroup§Â?Ă’´Lš Â˜Ăœ Š"3MatchObject ÂĽ groups() ˆ£¤kš group§ ~f¼ŠOLÂŤCharles "MatchObject ÂĽ start() !end()!span() !group() Ă‘ÂŒÂąD4ꐤLÂŤgroup Ă’è§0o´ 3 § Â…´"ÂŽꐤLš o iĂŽG"l1 mŠOê§Â˜ † regexp ÂĽ  ÂŒ group ꧤ¹§ ~fÂĽm.start(1)LÂŤname §m.start(2) L ÂŤAddress ")Ă’´ÂŒÂąi@ §ÚžOÂŽgroup Ă’è§Ă’ĂŞĂŞ(  Â˜§~X: >>> re.compile("(a(b)c)d").match("abcd").groups() (’abc’, ’b’) >>> kĂź|)Ă’§êê(  Â˜§k´abc §, ´b"p.finditer(x) 3cÂĄ0 L§ÂŒÂą^ 5H{¤kĂŠ MatchObject" ÂĄ print ŠÊ^m.groups() 5‚ªz˜‡iĂŽG" Ă?Â?m.groups() ´Â˜Â‡tuple§Ă™ÂĽ z˜‡ ƒ´Â˜Â‡string"group Ă˜ ڍ^{§Â„ ÂŒÂąLÂŤO†§X: (\b\w+)\s+\1 Ă’Lš ĂŤYĂ‘y ߇Ó Ăźc" lÞ¥ ~f¼§w kĂš Â˜Â‡ÂŻK§^m.group(1) LÂŤname§ÊĂ˜Â˜Ă™§ Â… X J 3 O \ ˜ ‡group { § Ă’ I ‡ N ÂĄ ¤ k group Ă’ è " X J U

^m.group(’name’) 5LÂŤname {§@oĂ’Â˜Ă&#x;Ăľ "ڇ¯K´Ú )Ăť §w eÂĄ ~f: >>> p=re.compile(r"^name:(?P<name>.*)\n^Address:(?P<address>.*)\n" \ r"^telephone:(?P<telephone>.*)\n^email:(?P<email>.*)\n",re.M) >>> for m in p.finditer(x): annCharles@tom.com

1114Â?, 208Â?

Python ÆS)P


§3.3 regular expression ... print m.groups() (’ Charles’, ’ BUPT’, ’ 62281234’, ’ annCharles@tom.com’) (’ Ann’, ’ BUPT’, ’ 62284321’, ’ CharlesWang@peoplemail.com.cn’) >>> matchs=[m for m in p.finditer(x)] >>> matchs[0].group(’name’) ’ Charles’ >>> matchs[0].group(’address’) ’ BUPT’ >>> matchs[0].group(’telephone’) ’ 62281234’ >>> matchs[0].group(’email’) ’ annCharles@tom.com’ >>> matchs[1].group(’name’) ’ Ann’ >>> matchs[1].group(’address’) ’ BUPT’ >>> matchs[1].group(’telephone’) ’ 62284321’ >>> matchs[1].group(’address’) ’ BUPT’ >>> matchs[1].group(’email’) ’ CharlesWang@peoplemail.com.cn’ 3ڇ~f¼§^(?P<xxx>.*) “O (.*)§Ă’ÂŒÂą^m.group(’xxx’) ¢ĂšÂš group § Ă˜´^group Ă’è §3 ĂŠE, regexp žÿ§w AOk^"ڍÂ?{ ´python gC *Ă?§ĂšĂ™ÂŚÂ?{Ă˜oN§f`Perl 5 Jø aq ś§ ´Â? ¹• oNPython „´ 3 ڍ*Ă?"3LÂŤO† žÿ§Ă’^(?=<xxx>) 5Âżvk

regexp ĂœŠ"X: (\b\w+)\s+\1 Ă’Lš ĂŤYĂ‘y ߇Ó Ăźc"ÂŒÂąU ¤ Â?§(?P<n>\b\w+)\s+(?=<n>)§´Â˜Â‡Âżg"„kÂ˜ÂŤÂ?Y§¡ĂœuŽ²^group Ă’è

§Â?´ÂŽO\˜‡group ´qĂ˜ÂŽKÂ? 5 Ă’è^S"⊠‰Non-capture group" O\ ˜‡group§ ´Ă˜Â?ŒŠ Ă’è§ ´vkÂ?{3MatchObject ڇgroup š ĂœŠ "^(?:...)5LÂŤÂ˜Â‡Non-capture group"Ù¼: LÚ)ĂťÂ?Y *Ă?Â? {"ĂšĂ˜´Â‡Ă?Â?{"

§3.3.8 Compile Flag 3^re.compile RegxObject žÿ§ÂŒÂąk˜ flag ^5N RegxObject Â? [A " annCharles@tom.com

1115Â?, 208Â?

Python ÆS)P


n Python ~^  DOTALL§S IGNORECASE§I LOCALES§L MULTILINE§M VERBOSE§X

4. š ?ÂżiĂŽ§Â?)†1ĂŽ\n Ă‘ÂŒ 4\w!\W!\b!\B Ăš clocale˜— Ăľ1 ª§Â?KÂ?^Ăš$ verbose ÂŞ

§3.4 ^struct ÂŹ?n ?›êâ C Šó §S ÂŒUkĂš ²{§½Ă‚˜‡struct §,

† ^e¥ �ª?n"

struct{ ... } header; write(fd,(void*) &header,sizeof(struct)); read(fd,(void*) &header,sizeof(struct)); 3Ă– ?›ŠÂ‡§X(Ă‘§ã¥§ã” §ŒÂ‚Â˜Â„Ă‘k˜‡ŠÂ‡ĂžÂ‚ÂŞ"ڍÂ?{4 Â?¡^"„k3?n äĂ?&§S žÿ§Â?´Êk^ "Python Â?kaq ?nÂ?{" Â…ĂŠ{Ăźk §Â?‡struct ÂŹÂĽ pack§unpack§Ăšcacsize Ă’t½ "ÂŚ^ڇ ÂŹ žÿ§þ I‡ÊC Šók

)"w‡~f: $cat a.c #include <stdio.h> struct testheader{ int version; char tag[4]; } ; struct testheader header={0x00010002,"WAVE"}; int main(int argc, char **argv) { FILE * fp = fopen("test.dat","wb"); if(!fp) return 1; fwrite((void*)&header,1,sizeof(header),fp); fclose(fp); return 0; } $gcc -o x a.c $./x $xxd test.dat 0000000: 0200 0100 5741 5645 annCharles@tom.com

1116Â?, 208Â?

....WAVE Python ÆS)P


§3.4 ^struct ÂŹ?n ?›êâ ˜‡C §S§ ˜‡ŠÂ‡Ăž"Â?šÂ‡ &EĂšÂ˜Â‡iĂŽ~Ăž"xxd ÂŒÂąwÂŤ ?›Š ‡"little endian ‚ª" >>> import struct >>> data = open(’test.dat’,’rb’).read() >>> start,stop = 0 , struct.calcsize(’hh4s’) >>> ver1,ver2,tag= struct.unpack(’hh4s’,data[start:stop]) >>> ver 2 >>> subver 1 >>> tag ’WAVE’ ڇ~f¼§ÂŒÂą ?› ŠÂ‡Ăž&E"unpack 1Â˜Â‡ĂŤĂŞ^uÂŁĂŁstruct ( §1 ‡Íê´Ă‘\ ?›êâ" ‚ª½Ă‚XL3.4-4" L3.4-4kA‡Š 5Âż /Â?" ‚ª x c b B h H i I l L q Q f d s p P

C Šóa.

Python a.

char char signed char unsigned char signed short unsigned short signed int unsigned int signed long unsigned long signed long unsigned long float double char[] char[] void*

Ăƒ(LÂŤWÂżi!) Ă?Â?1 iĂŽG Integer Integer Integer Integer Integer Integer Integer Integer Integer Integer Float Float String String Integer

L 3.4-4: struct ÂŹÂĽ ‚ª½Ă‚

annCharles@tom.com

1117Â?, 208Â?

Python ÆS)P


n Python ~^ ÂŹ iĂŽ @ = < > !

i!^S

�ÚÊà �ª

native native little-endian big-endian network (= big-endian)

native standard standard standard standard

L 3.4-5: i!^S½Ă‚ • q§Q Â?k3Ă…ĂŹ|Âą64  ÜŠ žÿâk¿Â" • z‡‚ªcÂĄÂŒÂąkÂ˜Â‡ĂŞi§Lþ‡"XÞ¥~fÂĽÂŒÂą ¤" >>> struct.unpack(’2h4s’,data[start:stop]) (2, 1, ’WAVE’) • x LÂŤW¿ §vkĂ‘Ă‘(J"X >>> struct.unpack(’xxh4s’,data[start:stop]) (1, ’WAVE’) • s ‚ªÒ´LÂŤÂ˜½ Ă? iĂŽG§4sLÂŤ Ă?Â?4 iĂŽG" ´p Ă˜Ă“§ŒL ÂŤâ€œPascal Stringâ€?§ ?›ê⼧ ˜‡i!LÂŤiĂŽG Ă?§ ÂŒ256§ ¥â´ T Ă? iĂŽG" • P ^ĂšĂ…ĂŹÂƒ' Ă?§=†˜‡Â? "64  Ă…ĂŹ^long integer§32  ^integer" 3"ÂŽ Âœše§struct Šâ /Ă…ĂŹ i!^S=†§Â?Ă’´`§Intel CPU ^little-endian§SPARC CPU ^big-endian"i!ĂŠĂ Â?ÂŞĂš / C Šó?ĂˆĂŹÂĽ ĂŠĂ Â?ª´Â˜Â— "Â„ÂŒÂą^‚ª¼ 1˜‡iĂŽ5UCڍÂ?ª§XeL3.4-5: ~X: >>> data ’\x02\x00\x01\x00WAVE’ >>> struct.unpack(’!hh4s’,data) (512, 256, ’WAVE’) >>> struct.unpack(’<hh4s’,data) (2, 1, ’WAVE’) pack Ăšunpack ĂśÂŠÂƒÂ‡"

§3.5 ^Cmd ÂŹ? {Ăź ¡-1 Â? ÂŒÂą3/usr/lib/python2.2 eĂŠ cmd.py§^ÂŚÂŒ¹Ê{Ăź ? ˜‡¡-1 Â?§ ^uÂŒ.§S ÿà §½Ü† Ă’ÂŚ^ڍ Â?§ÂŠÂ? ª ÂŹ" annCharles@tom.com

1118Â?, 208Â?

Python ÆS)P


§3.5 ^Cmd ÂŹ? {Ăź ¡-1 Â? Â? ¯„mu§S .§^uÂą mu Ă„:§Ú {Ăź Â?rÂŒ Â…¡^§~ XGDB§Python p)ºÏ§Bash §Octave §Gnuplot § Ă’´Ú Â?" Cmd ÂŚ^ readline ¼§Ú ¤k¹Þóä¼~^ ¡-1?6¡-Ă‘´üŠ^ § „k{¤?6ĂľU"XL3.5-6ÂĽÂ?š ~^ ˜ ĂľUÂ…"Ăš 3¤kÂŚ^readline óä Ă‘´Ă?^ §Â?)Þ¥J gnuplot §S" ÂŁĂ„ 1Ă„ ÂŁĂ„ 1— Ă­Ă˜ 1Ă„ Ă­Ă˜ĂžÂ˜Â‡cŠ ĂŠbĂ­Ă˜ SN Â•Â†ÂŁĂ„Â˜Â‡Â‚ •mÂŁĂ„Â˜Â‡Â‚ Â•Â†ÂŁĂ„Â˜Â‡Ăźc •mÂŁĂ„Â˜Â‡Ăźc

C-a C-e C-u C-w C-y C-f C-b M-f M-b

L 3.5-6: ¡-1?6 ÂŻ$Â… Cmd ´Xd ĂĄ §4¡ÂŒÂŻÂ˜¯§cmd.py k269 1§Â„Â?)47 1 Š "ĂŤ cmd.py Â“è Â?Ăľ &E"

§3.5.1 {Ăź ~f “èdemo cmd.py XeÂľ # l cmd.py \ class Cmd from cmd import * # ½Ă‚ Cmd fa class CmdInterface(Cmd): # ½Ă‚˜‡¡# argc ´Ú‡¡- ¡-1ĂŤĂŞ def do_say_hello(self,argc): print "hello! " + argc if __name__=="__main__" : # welcome ½Ă‚XĂš  H&E welcome ="welcome a simple command interface demo demo" # ?\¡-)Âş ĂŒÂ‚§Ă–˜‡¡-¿…)º‰1" CmdInterface().cmdloop(welcome) $1(J: annCharles@tom.com

1119Â?, 208Â?

Python ÆS)P


n Python ~^ ÂŹ %python demo_cmd.py welcome a simple command interface demo demo (Cmd) help Undocumented commands: ====================== help say_hello (Cmd) say_hello hello! (Cmd) say_hello Charles hello! Charles z˜‡¡-Ă‘´Â˜Â‡¤ Ÿê§XJ½Ă‚ do_foo Ăš ˜‡¤ Ÿê§@o- foo ڇ¡- žÿ§Ă’ÂŹN^do_foo"argc Ă’´foo xxx ¥‹ ¤k¡-1ꐤxxx" cmd_loopLÂŤ?\¡-ĂŒÂ‚§Ă– ˜‡¡-1§)º¡-1§Ê Ăœ¡ ¤ Ÿê§ ‰1¤ Ÿê"cmd_loop „‰Êþٌ ÂŻÂœ"~XN^readline ÂĽ " Cmd "ÂŽ Jøhelp ¡-§^uJø3‚Â?Ă?"

§3.5.2 ½Ă‚%@¡XJĂ‘\ ˜‡¡-§ÊĂ˜ ĂŠA ¡-?nŸê§Ă’‰1default(self,line) Ă™ ÂĽline LÂŤĂ‘\ ¡-1" Cmd Jø %@Ċ´ print ’*** Unknown syntax:’, line

§3.5.3 ?nEOF Ăž ÂĄ § S k ˜ ‡ f ž § Ă’ ´ Ă˜ U ~ ò Ă‘ " ˜ „ § S - Š ‡ ( ĂĽ ĂŽ Ă’EOF (Control-D)§L§SATòĂ‘ "XJ % echo "say_hello Charles" | python demo_cmd.py Ă’ÂŹkkĂŒÂ‚" \ĂžEOF ?nĂ’ÂŒÂą ~òĂ‘ " def do_EOF(self,arc): return 1 do_EOF ÂŹ3- ŠÂ‡(ĂĽ žÿ ‰1"3lIOĂ‘\Ă–\ žÿ§Control-DLŠ ‡(ĂĽ"?Ă›Â˜Â‡do_xxx ŸêXJÂˆÂŁĂ˝ÂŠ§Ă’L‡òĂ‘cmd_loop" Â„ÂŒÂąĂ‘\“ exitâ€? òĂ‘" annCharles@tom.com

1120Â?, 208Â?

Python ÆS)P


§3.5 ^Cmd ? {ß ¡-1 � def do_exit(self,arc): return 1

§3.5.4 ?n˜¡3"ÂŽ Âœše§{Ăź UÂ˜Â‡ÂŁÂ?§Ă‘\˜‡˜1§L‰1ĂžÂ˜^¡-" XJÂŽUCڍ?n§@o½Ă‚eÂĄ Ÿê: def emptyline(self): pass Ă‘\˜1 žÿ§Â‰1emptyline"

§3.5.5 ¡-1gÄÖà ڇþU´ åĂš< ĂľU§Œ^Bash <~~ÂŚ^tab Â…§^ugĂ„Ă–à ŠÂ‡Âś ¥§ĂšĂ™ÂŚĂŤĂŞ" "ÂŽ Ă–Ă ĂľU´Ă–Ă c8š¼ ŠÂ‡ϴ" \\eÂĄ ŸêÂŒÂąUC"ŽÄŠ: def complete_say_hello(self,text,line,begingidx,endidx): x=["Charles","Smith","Tom"] return [ k for k in x if k.find(text)==0] XJĂ‘\“say helloâ€? Charles

Smith

UĂźgtab §Ă’ÂŹĂ‘y

Tom

^uJÂŤ^rĂ–à ¡-"XJĂ‘\“Câ€? ,

Utab Â…§Ă’ÂŹgĂ„Ă‘\“Charlesâ€?"

complete_say_hello ==^usay_hello ¡- gĂ„Ă–Ă ĂľU"text LÂŤ^rĂ‘\ Ăźc mĂž§lineLÂŤ c¡-1§beginidx LÂŤtext 3line ÂĽĂ‘y  Â˜"endidx LÂŤtext 3lineÂĽ (ĂĽÂ Â˜"Ăš ĂŤĂŞÂ?^rJø v &E§^uJø¡-1Ă–Ă ĂľU" XJĂ˜F"^tab Â…5Ă–à ¡-§@oÂŒÂąĂ?LinitŸêUCڇ…" x=CmdInterface("?") UÂ?“?â€? ^u¡-1Ă–Ă "

§3.5.6 UCIOĂ‘\Ă‘Ă‘ init „ ÂŒ Âą J ø U C I O Ă‘ \ Ăš I O Ă‘ Ă‘ Ă… ÂŹ " " ÂŽ Âœ š e § ÂŚ ‚ Š O ´sys.stdin Ăšsys.stdout" annCharles@tom.com

1121Â?, 208Â?

Python ÆS)P


n Python ~^ ÂŹ

§3.5.7 UCJÂŤĂŽ Cmd "ÂŽJÂŤĂŽ´â€œCmdâ€? §ÂŒÂąĂ?LUCprompt ĂĄ5§UC¡-1JÂŤĂŽ"~ X: x=CmdInterface() x.prompt="?" x.cmdloop(welcome)

§3.5.8 Jø3‚Â?Ă?ĂľU [% Ă–܎²uy§help ¡- Ă‘Ă‘ÂĽk“Undocumented commands:â€?" Cmd 3‚Â?Ă?r¡-ŠÂ?nÂŤ" • Undocumented commands: Ă’´vkJø?Ă›Â?Ă?&E ¡-" • Documented commands: Ă’´JøÂ?Ă?&E ¡-" • Miscellaneous help topics: Ă’´Jø Â?Ă?&E§ ´vkÂ†ÂƒĂŠA ¡-"^uJøʘ|¡-§½Ü ‰˜ Â‡ĂŒKtopic Â?Ă?" Ă?Â?¡Â‚vkÂ?say_hello Jø?Ă›Â?Ă?&E§@oÂŚĂ’´Undocumented commands. XJ¡Â‚½Ă‚¤ Ÿê: def help_say_hello(self): print """ say_hello [<person>] say hello to somebody """ say_hello Ă’ C ¤ Documented commands. 1help_say_hello"

Ă‘ \“ help say helloâ€? Ă’ ÂŹ ‰

XJ¡Â‚½Ă‚: def help_test(self): print """ this is only a test topic """ “testâ€? Ă’¤Â?Miscellaneous help topics"ÂŒÂąĂ‘\“help testâ€? ‰1help_test ÂŒÂąĂ?L“?testâ€? “?say helloâ€? ˜ J" annCharles@tom.com

1122Â?, 208Â?

Python ÆS)P


§3.5 ^Cmd ? {ß ¡-1 �

§3.5.9 $1Shell ĂľU ¡Â‚½Ă‚: def do_shell(self,argc): import os os.system(arg) ÂŒÂąĂ‘\“shell lsâ€? ½Ü“!lsâ€?§Â‰1shell ¤ Ÿê"

§3.5.10

getattr ĂľU ÂŚ^

getattr Ÿê ÂŚ^§´Cmd ÂŹÂĽ 'Â…Eâ" ¡Â‚ ˜„ ¡-1)Âş §S§Ă‘´Â‡Â‰Â˜Â‡L§^5ĂŠAz˜‡¡-§ĂšÂƒA ¡-?nŸê§ ´Cmd ¼§Â?‡½Ă‚¡-?nŸêĂ’ÂŒÂą §´No¢y QÂş def onecmd(self, line): # line ´^rĂ‘\ ¡-1" # r line Š)¤Â?¡-ĂœŠĂšĂŤĂŞĂœŠ" cmd, arg, line = self.parseline(line) try: # Âą do_cmd ‚ªmĂž ŸêÊ–" func = getattr(self, ’do_’ + cmd) except AttributeError: return self.default(line) # N^ func ʖ" return func(arg) dÞ¥ Â˜ĂŁÂ“è§ÂŒÂąw getattr ÂŚ^´'Â…"ڍA5ÂŚ §SÂŒÂąĂ„ ʖ ¤k¤ " Ăš ĂŁ “ è k ˜ ‡ ÂŻ K § Ă’ ´ v k ĂŠ func Š u § X J U äcallable(func) Ă’ ÂŹ Â? Ă? § Ă˜ , § f a ½ Ă‚ do_cmd ´ ¤ Âź ĂŞ § ´ ¤ C Þ§@oĂ’ÂŹ )É~" Ă“ §Â?Ă?&E )¤§Â?ÂŚ ĂŽhelp_cmd ‚ª ¤ Ÿê" Â?Ă? ŠaÂ?´Ăšgetattr k'X" • Undocumented commands: kdo_cmd ‚ª ¤ Ÿê§ ´vkhelp_cmd ‚ª ¤ Ÿê" • Documented commands: kdo_cmd ‚ª ¤ Ÿê§Â?khelp_cmd ‚ª ¤ Ÿê" annCharles@tom.com

1123Â?, 208Â?

Python ÆS)P


n Python ~^ ÂŹ • Miscellaneous help topics: vkdo_cmd ‚ª ¤ Ÿê§ ´khelp_cmd ‚ª ¤ Ÿê" Ăš § §S ÂžĂżĂ˜I‡Â?ÂˆÂŤa. Â?Ă?Ÿê‰Ša§§S Ă’Jø v & E§^uŠa"

§3.6 ?n¡-1À‘ Ă™GUnix <Ă‘ §Unix ekÊþ¡-Ă‘´ÂŒÂą?nÊþÊþ¡-1À‘§^u› ›§S 1Â?§ĂšÂ?²§S‡?n ŠÂ‡ϴ"X: ls -l -a grep -i a somefile getopt Ă’ ´ Â? B § S ? n ¡ - 1 ĂŤ ĂŞ ˜ ‡module "getopt.py 3/usr/lib/python2.2/ e

§3.6.1 ˜‡{Ăź ~f “èdemo_getopt.py # \ getopt from getopt import * import sys opts,args = getopts(sys.argv[1:],"a","--all") print opts print args $1(J: %python demo_getopt.py -a f [(’-a’, ’’)] [’f’] %python demo_getopt.py [] [] %python demo_getopt.py --all [(’--all’, ’’)] [] %python demo_getopt.py -x Traceback (most recent call last): File "demo_getopt.py", line 4, in ? annCharles@tom.com

1124Â?, 208Â?

Python ÆS)P


§3.6 ?n¡-1À‘ opts,args = getopt(sys.argv[1:],"a","all") File "/usr/local/lib/python2.3/getopt.py", line 91, in getopt opts, args = do_shorts(opts, args[0][1:], shortopts,args[1:]) File "/usr/local/lib/python2.3/getopt.py", line 191, in do_shorts if short_has_arg(opt, shortopts): File "/usr/local/lib/python2.3/getopt.py", line 207, in short_has_arg raise GetoptError(’option -%s not recognized’ % opt, opt) getopt.GetoptError: option -x not recognized lÞ¥ ~fÂŒÂąwĂ‘§getopt I‡k3 ‡ÍêÑ\" • sys.argv[1:] ‡)Âş ¡-1À‘"Ă˜Â?)¡- " • "a" åÀ‘ åÀ‘´^˜‡“-â€? ŠÂ… À‘œ¥§Ă’–ls -a ÂĽa ˜ "Â?^˜‡i1LÂŤ" • ["all"] LÂŤ À‘" XJÂ?kÂ˜Â‡Ă€Â‘§@o҆ ¤Â˜Â‡iĂŽG§XJĂ˜Â?˜‡ À‘§@o҇ ¤iĂŽG list" ĂƒĂ˜ åÀ‘§Ă‘Ă˜Â?)cÂĄ “-â€? ½Ü“–â€?" getopt ˆ ÂŁ ˜ ‡tuple§ š k Ăź ‡ ƒ §opts,args§args L ÂŤ v k ) Âş L sys.argv[1:] ĂœŠ§Â˜Â„LÂŤI‡?n ŠÂ‡ϴ" opts LÂŤuy À‘§´Â˜Â‡list§list ÂĽ z˜‡ ƒ´Â˜Â‡tuple§LÂŤÂ˜Â‡pair, (opt,val)§opt LÂŤ3¡-1ÂĽuy À‘ ϴ"val LÀ‘¤ÊA ĂŤĂŞ"XJ´ ˜iĂŽG§LÂŤTÀ‘vkĂŤĂŞ"opts ¼À‘Ñy ^SĂš¡-1ÞÑy ^S´Â˜ "#NÀ‘­EĂ‘yĂľg" XJ3¡-1ĂžuyĂ˜U)Âş ꐤK Ă‘GetoptError É~"GetoptError ÂĽ msgĂĄ5LÑ† £ã§optĂĄ5LÂŤĂ˜U)Âş À‘ "

§3.6.2 ‘kĂŤĂŞ ¡-1À‘ ĂŠuåÀ‘§3À‘ getopt UÂ?"

ÂĄÂ‹Â˜Â‡kĂ’LÚ‡À‘I‡Íê"~X¾Þ‡˜‡~fÂĽ

getopt(sys.argv[1:],"a:","all") XJ¡-1ÂĽvkJøÀ‘§Â˜ ÂŹ Ă‘GetoptErrorÉ~"$1(J: annCharles@tom.com

1125Â?, 208Â?

Python ÆS)P


n Python ~^ ÂŹ %python demo_getopt.py -a Traceback (most recent call last): File "demo_getopt.py", line 4, in ? opts,args = getopt(sys.argv[1:],"a:","all") File "/usr/local/lib/python2.3/getopt.py", line 91, in getopt opts, args = do_shorts(opts, args[0][1:], shortopts, args[1:]) File "/usr/local/lib/python2.3/getopt.py", line 195, in do_shorts opt) getopt.GetoptError: option -a requires argument %python demo_getopt.py -a b [(’-a’, ’b’)] [] ĂŠu À‘§K‡3À‘ϴ

ÂĄ\˜‡ Ă’"~X:

getopt(sys.argv[1:],"a:","all=") (J´: %python demo_getopt.py -a b --all xx file1 file2 [(’-a’, ’b’), (’--all’, ’xx’)] [’file1’, ’file2’]

§3.6.3

optparser ÂŹ

optparser ´Python 2.3 ‘ ˜‡rÂŒ!(š!´^!´*Ă? ¡-1)ºÏ"ÂŚ ^optparser §Â?^ĂŠ “è§Ă’ÂŒÂąÂ?\ §SO\61 §;Â’ ¡-1 Â?" ÂŚ'getopt ÂŹÂ?Ă?^" Ăšpk˜‡{Ăź ~f #!/usr/bin/env python # simplyOptparser1.py from optparse import OptionParser parser = OptionParser(version="%prog 0.1 ") parser.add_option("-f", "--file", dest="filename", help="write report to FILE", metavar="FILE") parser.add_option("-q", "--quiet", action="store_false", dest="verbose", default=True, help="don’t print status messages to stdout")

annCharles@tom.com

1126Â?, 208Â?

Python ÆS)P


§3.6 ?n¡-1À‘ (options, args) = parser.parse_args() D = vars(options) for i in D: print i,"=",D[i] Ăš §\ §SҔ¤kGNU e óä˜ §kĂŠĂľ option ÂŒ¹Œ^" %./simplyOptparser1.py -f output --quiet verbose = False filename = output %./simplyOptparser1.py -qf output verbose = False filename = output %./simplyOptparser1.py -q --file=output verbose = False filename = output %./simplyOptparser1.py --quiet --file=output verbose = False filename = output %./simplyOptparser1.py --help usage: simplyOptparser1.py [options] options: --version show program’s version number and exit -h, --help show this help message and exit -fFILE, --file=FILE write report to FILE -q, --quiet don’t print status messages to stdout %./simplyOptparser1.py --version simplyOptparser1.py 0.1 % §SwĂĽ5ĂŠ;Â’" optparser Ong optparser ÂŹ OngĂŠÂŒ§Ă?ÞÉ Unix ĂšGNU e óä8 KÂ?"y0 ˜

âŠ: • argument (¡-1ĂŤĂŞ) annCharles@tom.com

1127Â?, 208Â?

Python ÆS)P


n Python ~^ ÂŹ %ls -l /usr Ă™ ÂĽ-l usr Ă’ ´ ¡ - 1 ĂŤ ĂŞ "sys.argv ´ ˜ ‡list § ^ u L ÂŤ ¡ - 1 " ~ f ¼§sys.argv Ă’´ [’ls’,’-l’,’/usr’] ¡-1ĂŤĂŞĂ’´sys.argv[1:] §Ă?Â?sys.argv[0] L¡- " • option (¡-1À‘) § S 3 ‰ 1 ž Ăż § largument & E § ^ 5 N § S ‰ 1 " D Ăš Unix ĂšGNU ¡-1Š{´: -q -f

--file --quiet

˜‡~Ă’§ ÂĄÂ‹Â˜Â‡ĂĄĂ€Â‘§½Ü߇~Ă’§ ĂœÂż3˜ü§X-qf optionparser Ă˜|ÂąeÂĄ Š{"

ÂĄÂ‹Â˜Â‡ À‘"ĂľÂ‡ĂĄĂ€Â‘ÂŒÂą

• ˜‡~Ă’ ¥‹‡L߇iĂŽ¹Þ åÀ‘§X-pf§Ă„KĂ’ŠĂ˜Â˜Ă™´-p -f Ăź ‡À‘§Â„´-pf Â˜Â‡Ă€Â‘" • ˜ ‡ ~ Ă’ ÂĄ ‹ ˜ ‡ Ă€ ‘ § X-file § ‹ Ăž ÂĄ a q § Ă’ v k Â? { Š ˜ Ă™

-file ´Â˜Â‡Ă€Â‘„´-f -i -l -e o‡À‘º • ^\Ă’§Â“O~Ă’§X+f §+rgb §Ă˜ĂœS." • ^ m“O~Ă’§~X/l §/rgb §Ú´Windows ĂšVMS ^{§ ´3Unix e mLÂŤ8š§¤¹ls /l— Ă’ŠĂ˜Â˜Ă™´/l ´Ă€Â‘§Â„´8šœ¥ " • option augument(À‘Íê) ”-f outputfile Ăš Ă€ ‘ § ÂĄ ‹ ˜ ‡ ĂŤ ĂŞ §outputfile § L ÂŤ Ă€ ‘ ĂŤ ĂŞ"-foutputfile Ăš-f outputfile Ă‘Â˜ "k Ă€Â‘Ă˜I‡ꐤk À‘7 L‰ÑÍê" ´Ă„I‡optional option argument (ÂŒĂ€ À‘Íê)QÂşÂ?Ă’´`§XJ ¥‹ ĂŤ ĂŞĂ’@Â?ΫÀ‘ꐤXJvk§Ă’@Â?À‘vkĂŤĂŞ"~X§bX-a À‘ ÂĄ koptional option argument: ls -a xxx -b LÂŤ-a ‘kĂŤĂŞxxx § |ls -a -b| LÂŤ-a vkĂŤĂŞ" ´§XJ´ls -ab @o¡Â‚TNo@Â?QºŠĂ˜Â˜Ă™ §¤ Âąoptionparser ÂŹĂ˜|Âąoptional option argument " annCharles@tom.com

1128Â?, 208Â?

Python ÆS)P


§3.6 ?n¡-1À‘ • positional argument ( Â˜ĂŤĂŞ) 3¡-1Í꼧Ă˜ À‘¹ §Â?e Ă’´positional argument §Â˜Â„^uLŠ ‡ϴ"~XÂľ ls -l /usr /lib Ù¼¼[’/usr’, ’/lib’] Ă’´positional argument " • required option (7 À‘) ´Â?^r7LJø À‘"Ú´Â‡Â€ĂŒÂż"XJ\ §S‡Œ^r7LJø˜

option § @ o Ăš ´ ˜ ‡ ĂŠ Ă˜ Ă? Â? O § ĂŠ k ^ r ÂŹ F % Ă‘ \ ¤ k \ ‡option " ,\XJ˜½Â‡Ăšo‰§Â?´qÂ?{ " ~f: ¡-1 Âľprog -v --report /tmp/report.txt foo bar ¡-ϴ : prog argument ¡-1ĂŤĂŞ: -v --report /tmp/report.txt foo bar option : -v --report option argument : /tmp/report.txt positional argument : foo bar O¡-1 Â?RÂŻ • ‡Œ^rJø 7LJø &E Ă?"XJvkoption §§SÂ?ÂŒÂą ~$ 1"ÂŒþê Unix ĂšGNU óäĂ‘´Ú "Ă˜ find, tar, dd §Êþ<1¾Ú

§S ¡-1 Â?Ă˜IO§N´Ăšü¡ " • Ă˜Â‡k7 À‘required option "XJ^r7LJøÚ &E§@oÂŚÂ‚Ă’Ă˜´ÂŒk ÂŒĂƒ À‘ § ´positional argument " • z‡option Ă‘ATkĂœn %@Š" • ĂĄoption ƒp Ăœ§Â˜Â˜ĂŠA"ĂĄ ´u pÂŞĂ‘\Â?B§ ÂŒÂąJp §S ÂŒĂ–5"¤¹§ pÂŞ shell ¼§Ă‘\ls -l ' Ă?" ´31?n §S ¼§ Ă? ¤--long " ~X: cp ¡cp SOURCE DEST cp SOURCE ... DESTDIR \Ă˜^?ÛÀ‘§cp oU ¤Œ ĂŒÂ‡?Ă–§r˜‡ŠÂ‡Â€ ¤Â?,˜‡ŠÂ‡§½Ür˜ ̊‡€ ˜‡8š¼ " ,§\Â?ÂŒÂąÂ?½ÊþÀ‘§^uÂ?½´Ă„ 3ŠÂ‡  §´Ă„ 3?Užm§´Ă„‹‘ó §´Ă„48€ 8š § ´ŒÂ‚Ă‘Ă˜KÂ?cp $1" annCharles@tom.com

1129Â?, 208Â?

Python ÆS)P


n Python ~^ ÂŹ positional argument ˜„´§S7I &E" ,§k Êþ§SĂ˜I‡?Ă›&E§Â? ÂŒ¹ÊĂ? $1§~Xcat, sort, cut, grep, sed, awk, head, tail, ed, uniq, fold, wc, fmt,split, od, xxd, sum, §ŒÂ‚Ă‘ Ă‚positional argument ÂĽ ÍêŠÂ?Ă‘\ ŠÂ‡œ¥§ ´ XJvkÂ?½Ă‘\ŠÂ‡ œ¥§@oĂ’lIOĂ‘\Ă–"Ăš ¡-š~Ă?§Ăš+ ś Ăœ ĂĽ5§%ĂĽĂƒÂĄ" k §S§K7L‡‰ÑÚ &E§Xdiff, join, tr, Ă?Â?Ăš §S"

7 &E§Ă’Ă˜U ¤§ ?Ă–"X: diff 7L‡‰Ñ߇ŠÂ‡œ¥§Ă„KÂŚ' Â&#x;o Q? join ´r߇ŠÂ‡Ăœ¿§¤¹7L‰Ñ߇ŠÂ‡ϴ"tr ´Â€ĂˆĂľU§7L`²rÂ&#x;o Â€Ăˆ¤Â&#x;o§ŒâUóŠ"¤¹Ú 7 ÍêъÂ?positional argument" cut 3ĂšÂ˜:މ Ă˜Ă?§ %cut cut: you must specify a list of bytes, characters, or fields Try ‘cut --help’ for more information. ڴ˜‡~ §cut ˜½Â‡^rJø&E§N JĂ‘lĂ‘\ÂĽJĂ‘eZ "^rkþ Ă€J§Â?²Ui!byte§iĂŽcharacter „´iĂŁfield Ă€JÂ˜ĂœŠ"¡@Â?ATk˜‡%@ Ċcut -f 1 §Â?NĂšĂ˜´ÊĂ? Â˜Â‡Ă€J§½Ü%@Ċ´cut -b1 §cut -c1 § ´ Ăƒ¤¢§oƒATJø˜‡%@ Ċ§OĂş ^r %§O4^r” F%" b §\ §S‡Œ^rJø17 Ă˜Ă“ &E§§SâU¤þ óŠ§ĂƒĂ˜\JøÂ&#x; o .¥§´command line, GUI Ă‘Â˜ §@oA vk<kF%$1\ §S§$–Â? )\gC" ,§#N^rJø option þ§\ §S (š5Ă’ Ă?§§SÂ?Ă’ J¢y" Jøoption Â?ªÊþ§ÂŒ¹´ ˜ŠÂ‡ Â?ª§ÂŒ¹´3èßÞĂ€JPreferences §, Ă€JÂ˜Â‡Ă€Ăœ"„Œ¹´¡-1ĂŤĂŞ Â?ª§ĂƒĂ˜=ÂŤÂ?ÂŞÂ?Ă?§Â‡ % O§Ă„KĂ’N´ 'Ăž§Â?)\gC"Ž–k §S‰Ñ1000 ‡option §, 4\?UÙ¼ ˜‡§1ĂŠ @‡option Ă’ʤ¯ "JøÂ?Ă?&EÂ?ÂŹ-<ĂžÂŒ" Ă„ ^{ 1. Ă„k import optparse parser = optparse.OptionParser() ĂšÂ‡Ă˜Jn)§kMĂŻÂ˜Â‡OptionParser ʖ" 2. Ă™g parser.add_option("-f","--file",...) O\option " annCharles@tom.com

1130Â?, 208Â?

Python ÆS)P


§3.6 ?n¡-1À‘ 3. )º¡-1 (options, args) = parser.parse_args() options ¼šk¤k¡-1Jø option &E"args ´positional argument &E" y3§­:?Ă˜add_option "Ă™ÂĽĂžĂźÂ‡ĂŤĂŞĂ˜Ăł Â’§Â˜Â‡LÂŤĂĄoption§Â˜Â‡L ÂŤ option " ĂśÂ˜Â˜ĂŠA" ÂĄ ĂŤĂŞJøÂˆÂŤĂľU: 1. I‡Íê option " ~X: parser.add_option("-f", "--file", action="store", type="string", dest="filename") Ù¼action LÂŤN ?noption §Þ¥ ÂżgĂ’´`: r-f ½--file À‘ ‘Íê Â?filename CĂž"~X:

¥ À

args = ["-f", "foo.txt"] parser.add_option("-f", "--file", action="store", type="string", dest="filename") (options, args) = parser.parse_args(args) print options.filename ҏ‹<Ă‘5foo.txt "a.´iĂŽG" type Â?²a.§Â„ÂŒ¹´int ½Üfloat "%@Š´string "XJuyĂŤĂŞĂ˜ĂŽĂœÂ?½ a.§@oҋ<ц&E§, òĂ‘§S" dest Â?² ;CĂž ϴ"%@Š´Ăš option ϴÂƒĂŠA "r option m Þ߇~Ă’ K§rÙ¼ ~Ă’C¤ey‚§Ă’´CĂž ϴ"އ~fÂĽĂ’´rƒ A CފÂ?options.filename " 2. Ă˜I‡Íê option " r action = "store" U¤Â? annCharles@tom.com

1131Â?, 208Â?

Python ÆS)P


n Python ~^ ÂŹ action = "store_false" ½Ü action = "store_true" ~X: parser.add_option("-v", action="store_true", dest="verbose") parser.add_option("-q", action="store_false", dest="verbose") XJ¡-1ÂĽk-v ½Ü-q §Ă’ŠOrverbose ˜¤Â?True ĂšFalse" 3. option ĂŤĂŞ %@Š" XJvk ˜option ĂŤĂŞ %@Š§ Â…Â?vk3¡-1ÂĽuyTÀ‘§@oĂŠA CĂž ŠÒ´None "ÚávÂŒþêÂœše IΤ ´XJ\‡gC ˜%@ŠÂ? ´ÂŒÂą "eÂĄ ~fÂŒÂąUC%@Š" parser.add_option("-v", action="store_true", dest="verbose") parser.add_option("-q", action="store_false", dest="verbose", default=True) eÂĄ ~fĂšc˜‡~f J˜ " parser.add_option("-v", action="store_true", dest="verbose", default=True) parser.add_option("-q", action="store_false", dest="verbose") XJ´ parser.add_option("-v", action="store_true", dest="verbose", default=False) parser.add_option("-q", action="store_false", dest="verbose", default=True) @overbose %@Š´True "Ă?Â?

¥ ŠÊCXc¥ŠÊ %@Š"

4. )¤Â?Ă? eÂĄ ~fÂŹgĂ„)¤Â?Ă?&E" #!/usr/bin/env python # optparser.help.py from optparse import OptionParser usage = "usage: %prog [options] arg1 arg2" annCharles@tom.com

1132Â?, 208Â?

Python ÆS)P


§3.6 ?n¡-1À‘ parser = OptionParser(usage=usage) parser.add_option("-v", "--verbose", action="store_true", dest="verbose", default=True, help="make lots of noise [default]") parser.add_option("-q", "--quiet", action="store_false", dest="verbose", help="be vewwy quiet (I’m hunting wabbits)") parser.add_option("-f", "--file", dest="filename", metavar="FILE", help="write output to FILE"), parser.add_option("-m", "--mode", default="intermediate", help="interaction mode: one of ’novice’, " "’intermediate’ [default], ’expert’") parser.parse_args() $1(J: % ./optparser.help.py --help usage: optparser.help.py [options] arg1 arg2 options: -h, --help -v, --verbose -q, --quiet -fFILE, --file=FILE -mMODE, --mode=MODE

show this help message and exit make lots of noise [default] be vewwy quiet (I’m hunting wabbits) write output to FILE interaction mode: one of ’novice’, ’intermediate’[default], ’expert’

% `²: (a) gċ<ÂŚ^Â?{usage"Ù¼%prog ÂŹgĂ„C¤sys.argv[0] §L¡-Âś ÂĄ"usage %@Š´ ’usage : %prog [options]’ (b) O\z˜‡option žÿ§Â?½help §@o)¤ Â?Ă?¼Ò‹<ƒA & E"help %@Š´Â˜iĂŽG" annCharles@tom.com

1133Â?, 208Â?

Python ÆS)P


n Python ~^ ÂŹ (c) meta-variable ´ Â? 3 Â? Ă? & E ÂĽ J ø ĂŤ ĂŞ “ Âś c " ~ X Â? Ă? & E ÂĽ -mMODE -fFILE "ÂŒÂą^metavar 5Â?½"metavar %@Š´ option Âśi KÞ߇~Ă’§, C¤ÂŒ 5 " 5. Â?option Š| \ §S‡ ÉÊþoption žÿ§ Ă?rŒ‚Š¤eZ|§Ú Bu+n§ĂƒĂ˜ ʧSmu܄´ ª^r§ÚĂ‘´Â˜Â‡Ă?ĂŒÂż" ~f: #!/usr/bin/env python # opt.group1.py #!/usr/bin/env python # optparser.help.py from optparse import OptionParser, OptionGroup usage = "usage: %prog [options] arg1 arg2" parser = OptionParser(usage=usage) parser.add_option("-v", "--verbose", action="store_true", dest="verbose", default=True, help="make lots of noise [default]") parser.add_option("-q", "--quiet", action="store_false", dest="verbose", help="be vewwy quiet (I’m hunting wabbits)") parser.add_option("-f", "--file", dest="filename", metavar="FILE", help="write output to FILE"), parser.add_option("-m", "--mode", default="intermediate", help="interaction mode: one of ’novice’, " "’intermediate’ [default], ’expert’") # add a option group group = OptionGroup(parser, "Dangerous Options", "Caution: use these options at your own risk. "It is believed that some of them bite.") group.add_option("-g", action="store_true", help="Group option.") parser.add_option_group(group) parser.parse_args()

annCharles@tom.com

1134Â?, 208Â?

"

Python ÆS)P


§3.6 ?n¡-1À‘

$1(J: $./opt.group1.py --help usage: opt.group1.py [options] arg1 arg2 options: -h, --help -v, --verbose -q, --quiet -fFILE, --file=FILE -mMODE, --mode=MODE

show this help message and exit make lots of noise [default] be vewwy quiet (I’m hunting wabbits) write output to FILE interaction mode: one of ’novice’, ’intermediate’[default], ’expert’

Dangerous Options: Caution: use these options at your own risk. believed that some of them bite. -g Group option. $

It is

`²: (a) OptionGroup Âź ĂŞ Ă‚ n ‡ ĂŤ ĂŞ § ¤ ĂĄ parser ĂŠ – §group { ĂĄ ÂŁ ĂŁ § Ăšgroup Â?[ÂŁĂŁ"ÂˆÂŁÂ˜Â‡option group ʖ" (b) ,

”parser ĂŠÂ–Â˜ §Â?group ʖO\option "

(c) ^add_option_groupŸêr˜‡group O\ ˜‡parser ʖ¼" 6. ‹<‡ &E"Ăšusage aq§3MĂŻparser ʖ žÿ§Â?½version ꐤĂ’ÂŒÂą ‹<‡ &E §Ă“žgĂ„O\ -v --version ڇoption " ~XÂľ parser = OptionParser(usage="%prog [-f] [-q]", version="%prog 1.0") Ă“ %prog ÂŹC¤sys.argv[0] " annCharles@tom.com

1135Â?, 208Â?

Python ÆS)P


n Python ~^ ÂŹ

§3.7 'užm ÂŹ time ڇ ÂŹ3Ă˜Ă“ ² Ăžk¤Ă˜Ă“§¤¹£Â‡5Ă˜´ Ă?§ ´Â?k êŸê £‡5Ă˜Ă?§ÂŒþê„´ÂŒÂą " ÂŹÂĽ ِϴĂšIO C Šó Ÿêœ¥´Â˜ §¤¹Í ² Ăž ƒA C ŠóÍ ĂƒÞ´Âš~k^ " ykA‡âŠŠ )Âş: • epoch (žm :)§ÂƒĂŠuepoch žm´Â?lepoch mŠ§²L ÂŚĂŞ"epoch ž m´0 "Ă?Â?epoch ÂƒĂŠuepoch ²L 0 ÂŚ"3UNIX XĂš¼§epoch žm´1970 c1 1 F0 :0 Š0 ÂŚ" ÂŹÂĽ ŸêŠU?nÂ˜ĂŁÂžmS žm§=lepoch mŠ§ ˜‡žm:§Ú‡ž m:§Â†Ă…ĂŹĂž^uLžm êâ êk'X§¿Â…ĂšC Šó ¼Ÿêk'X"Ăš ´Ă?Â?OÂŽĂ…o´Œ^k 'AĂŞ5LÂŤÂ˜Â‡ĂŞÂŠ§Œo´k Â› §Ă˜ULÂŤĂƒ  ÂŒ ‰ŒS ¤kĂŞ"3UNIX XĂš¼§Ú‡ ÂŒÂŠÂ˜Â„´2038 c" • 2000 cÂŻK"Python ?nžm Ÿê§´Œ^C Š󼧤¹Â˜Â„Ă˜ÂŹk2000 cÂŻ K§Ă?Â?§Âžm LÂŤÂŚ^ÂƒĂŠuepoch ²L ÂŚĂŞ5LÂŤ "XJÂ? • oN {§ÂŒÂą wpython-lib Â?Ă?" • UTC (Coordiated Universal Time) § ÂĽĂšÂ˜Âžm§½Ü`GMT (Greenwich Mean Time) ‚ %£žm§ • DST( Daylight Saving Time) §LÂŤg-ž§C ¼ŸêÂŒÂą?ng-ž§äNNo ‰§´ÂŠâĂ˜Ă“/ÂŤ ˜k'X§Â˜Â„k˜‡XĂšŠÂ‡§^uÂŁĂŁg-ž 5K" ˜„XĂš+n ATŽ²Â‰Ă?ڇŠÂ‡ " gmtime() , localtime(), strptime() ÂˆÂŁÂŠ§Â„kasctime(), mktime() ,strftime() ĂŤĂŞĂ‘´Â˜Â‡tuple §Ă™¼šk9 ‡ ĂŞ"ڇ9 ‡ ĂŞ šĂ‚XL?? ˆ‡Ÿêƒm 'X"ĂŁ3-1`² ˆ‡Ÿêƒm 'X"

§3.8 socket ?§ §3.8.1 0 socket ´Œ^ ›Š2Â? ä?§Eâ"socket Â?´Â˜ÂŤ?§mĂ?&(IPC) Eâ" Â?N3, ² Þ§socket Ă˜´ ¯ IPC § ´XJ`ª² 5´Â˜Â‡ĂŒÂ‡gĂą 5U ´g‡gĂą žÿ§socket Â?N´\ Ă? Ă€Jƒ˜" Python ÂĽ socket ?§ĂšC Šó socket Â?´Â›ŠÂƒq "XJ\°Ă?socket ?§ Eâ§@oPython ¼§Ă˜ Python Ă„ Š{§A Ă˜^ÆSÂ&#x;o# Ă€Ăœ§Ă’ÂŒÂą^ | ? socket §S " annCharles@tom.com

1136Â?, 208Â?

Python ÆS)P


§3.8 socket ?§

¢ĂšÂŠ

ĂĄ5

‰Œ

0 1 2 3 4 5 6 7 8

tm_year tm_mon tm_mday tm_hour tm_min tm_sec tm_wday tm_yday tm_isdst

X1993 1 – 12 1 – 31 0 – 23 0 – 59 0 – 61 0 – 6, Monday is 0 1 – 366 0, 1 or -1

L 3.7-7: Lžm

time +timezone seconds(local)

seconds(UTC) -timezone ctime

localtime

mktime

string

gmtime

strptime strftime struct time(local time)

struct time(UTC)

ĂŁ 3-1: žmŸêƒm 'X

annCharles@tom.com

1137Â?, 208Â?

Python ÆS)P


n Python ~^ ÂŹ ÙÄk‰Ñ߇{Ăź ~f§,

Â?[0 Ÿê N^6§§Ăšz‡Ÿê Ă„ ^

{"

§3.8.2 {Ăź ~f Â?rĂ ~f Â?rĂ socket ?§§´' {Ăź "MĂŻTCP ĂŤ Â?{Xe: #/usr/bin/env python # simpleClient.py import sys,os import socket def main(): s = socket.socket(socket.AF_INET,socket.SOCK_STREAM) s.connect((socket.gethostname(),8000)) s.send("GET index.html\n") s.shutdown(1); sys.stdout.write(s.recv(1024)) s.close() if __name__ == "__main__": main() {Ăź Ă‘Ă–ĂŹĂ ~f # simpleserver.py import socket,sys,os,popen2 def main(): s = socket.socket(socket.AF_INET,socket.SOCK_STREAM) s.bind((socket.gethostname(),8080)) s.listen(1) clientsocket,clientaddress = s.accept(); clientsocket.send("welcome %s\n" % str(clientaddress)) data.send("%s"%str(arg)) clinetsocket.close() s.close() if __name__ == "__main__" : main() Â?rà ÚÑÖÏà ŸêN^6§ XĂŁ3-2 annCharles@tom.com

1138Â?, 208Â?

Python ÆS)P


§3.8 socket ?§ Your App Here(Python) Tkinter(Python Module) tkinter(C) Tk Widgets(C and Tcl) Tk(C) Xlib (C)

ĂŁ 3-2: Â?rà ÚÑÖÏà ŸêN^6§ ڇ6§ãk˜‡/Â?N´ )Ă˜)§Â‡5Âż"Ă‘Ă–ĂŹĂ socket k߇"Ă‘Ă–ĂŹĂ Â˜mŠMĂŻ socket Ă˜´^5uxêâ §Â?Ă˜´^5 Ă‚êâ "ÂŚÂ?˜ Š^Ă’´ Ă‚ĂŤ žΤÂ?Ă’´Â?rĂ s.connect Ÿê§, MĂŻÂ˜Â‡socket ^uĂ‚uêâ"accept Ÿê Š^Ă’´Xd"Œ¤þ ÂˆÂŁÂ˜Â‡socket §Â„kĂŠÂ? IP /ÂŒ"˜ ¤þÂˆÂŁÂ˜ ‡socket §@oĂ’Ă˜2ŠĂ‘Ă–ĂŹĂ ĂšÂ?rà §ßà PkĂ“ ĂľU socket §^uĂ‚uĂŞ â" Ă?d§Â˜Â‡Ă‘Ă–ĂŹÂŒÂąÂ?þ‡Â?rĂ Ă‘Ă–§Ă‘Ă–ĂŹ Éaccept z˜‡Â?rĂ ĂŤ ž Τ, §ÂˆÂŁÂ˜Â‡socket ^uĂšTÂ?rĂ?&"Â?Ă’´`§XJkn ‡Â?rĂšĂ‘Ă–ĂŹÂƒĂŤ {§Ă‘Ă–ĂŹĂ kn + 1 ‡socket § Â?rĂ Â?k˜‡socket " „k5Âż{lŸêښ{lŸê ÂŤO§recv ŸêĂšaccept Ÿê%@^‡eĂ‘´{l §Â?Ă’´`§ŒÂ‚Ă‘Ă˜ÂŹĂĄ=ˆ£§Â† kÂŒ Ă‚ êâ½ÜÂ?r ĂŤ žŒ§ŒÂ‚⏠ˆ£§Ă„KĂ’[ Ă˜Âˆ£§Ă˜Âšu)Ă™ÂŚÂ†Ă˜"ÂŒÂąUCsocket option §4Œ‚C¤Âš {lŸê§ŒÂ‚ÂŹĂĄÂ?ÂˆÂŁ"

§3.8.3 MĂŻsocket MĂŻsocket Ÿê´: socket(address_family,type,protocol_type) `²: 1. address_family ^5Â?½Â‡ĂŻĂĄ=˜asocket "ÂŒ¹´¹e~Ăž" ’AF_APPLETALK’, ’AF_AX25’, ’AF_BRIDGE’, ’AF_INET’, ’AF_INET6’, ’AF_IPX’, ’AF_NETROM’,’AF_PACKET’, ’AF_ROSE’, ’AF_UNIX’, ’AF_UNSPEC’, ’AF_X25’]  ~^ ,´ÂŒœ IP Æ §AF_INET "3Unix XĂš¼§AF_UNIX Â?´ ' ~^ §^5ĂŻĂĄUnix ?§mĂ?&" annCharles@tom.com

1139Â?, 208Â?

Python ÆS)P


n Python ~^ ÂŹ 2. type ^5Â?½Ă?&a." ’SOCK_DGRAM’, ’SOCK_RAW’, ’SOCK_RDM’, ’SOCK_SEQPACKET’, ’SOCK_STREAM’  ~^ ´SOCK_STREAM ^uï奕Í 6Ă?&§SOCK_DGRAM ^uï嚥• ĂŤ ŠĂ?&"XJ1˜‡Íê´AF_INET ž§ŒÂ‚ĂŠA ´TCP ĂšUDP " 3. protocol_type ^uÂ?½ Æa."ڇÍê´ÂŒĂ€ §Ă˜Â˜½Âš ‰§3ĂŻĂĄTCP socket ½ÜUDP socket žÿ§ŒÂ‚Â˜Â„Ă‘´0 "XJ1˜‡Íê´AF_INET §@o ڇÍê^5Â?½IP Â?Þ¼ protocol iĂŁ" 1 ‡Íê´SOCK_RAW žÿ§@ o1nÂ‡ĂŤĂŞÂŒ¹´?Ă›RFC 1700 ÂĽ5½ Ɠè" ĂŻĂĄÂ˜Â‡TCP socket ~^Â?{´: sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) ĂŻĂĄUDP socket ~^Â?{´¾ sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) ĂŻĂĄUnix Â?^u?¢mĂ?& socket Â?{´: sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)

§3.8.4 ”½socket socket ½Ă‚´: an endpoint of communication to which a name may be bound ¡ Â€ĂˆĂ’´: socket ´ĂšÂ˜Â‡Âśi”½ Ă?&Ă :" ”½(bind) ÂżgĂ’´rĂźÂ‡Ă€ĂœĂŠX3˜ü§;; ”3Â˜ĂĽ"”½socket k ‰ ‰socket ĂĽÂśi§4O<U ĂŠ ΤڌĂ?&" TCP socket ÂśiĂ’´IP /ÂŒ\Ă Â?Ă’"IP /ÂŒ^5IÂŁIP äÞÂ˜Â‡ĂŒĂ…§à Â? Ă’^5IÂŁÂ˜Â‡ĂŒĂ…S ˜‡?§" UDP socket ÂśiÂ?´IP /ÂŒ\Ă Â?Ă’§ĂšTCP aq" ´k˜:‡5¿§UDP Ă Â?Ă’ĂšTCP Ă Â?Ă’´ĂŽĂƒ'X " Unix Â? socket Âśi´ŠÂ‡ϴ"~X“/tmp/sock/â€? "^ls -l ¡-u ˜‡Š ‡ žÿ§Œ I“´â€œsrwx----â€? b Ă™  ÂŠ´700(8) (l?›)§â€œsâ€? LŒ´Â˜ ‡socket " TCP Server socket 7LĂšÂ˜Â‡IP /ÂŒĂšĂ Â?Ҕ½§Ă„KÂ?rĂ Ă˜ NoÚÑ Ă–ĂŹĂŻĂĄĂŤ "TCP Client socket Â˜Â„Ă˜^ĂšIP /ÂŒĂšĂ Â?Ҕ½§kXĂšgĂ„Š annCharles@tom.com

1140Â?, 208Â?

Python ÆS)P


§3.8 socket ?§ ˜‡IP /ÂŒĂšĂ Â?Ă’" ,§Â˜½Â‡Â”½Â?ÂŒ¹§ ´N´ĂšXĂš¼Ž²Œ^ socket Ă€ â" Unix Â? socket ĂšTCP aq"Â?´Ă‘ÖÏà ‡”½§Â?rĂ Ă˜Â‡Â”½" UDP 5Ă˜ŠServer ĂšClient "¤kĂ?&:Ă‘´Ê § ´XJÂ‡ĂŒĂ„ Ă‚êâ Â? Ă?&:§Â‡ÂŻk”½IP /ÂŒĂšĂ Â?Ă’§Ú ٌà :â u‰Œ êâÂ?‡ux @‡à Â?"XJĂ?&:´uxêâÂ? §@oÂŚÂŒÂąÂ?½Â”½ Ă Â?Ă’´0 §¿g´4X ĂšgĂ„Â?Ă™Š Â˜Â‡Ă Â?Ă’§ ĂŠÂ?Ă‚ \ êâÂ? žÿ§ŒĂ’ \ IP /ÂŒĂšĂ Â?

"lڇ¿ÂÞÚ§UDP 3äNA^ žÿ§qŠÂ?Server ĂšClient " ÂŒ¹Œ^getsockname Ÿê ˜‡socket ”½ Âśi" ”½Â˜Â‡TCP socket ~^Â?{´: sock = socket.bind((socket.gethostname(),port)) ”½UDP socket ~^Â?{´¾ sock = socket.socket((socket.gethostname(),port)) ”½Unix Â?^u?¢mĂ?& socket Â?{´: sock = socket.socket("/tmp/sock")

§3.8.5 ĂŻĂĄĂŤ Â?rĂ ĂŤ žŒ connect Ÿê ĂŤĂŞÂĽÂ?² IP /ÂŒĂšĂ Â?Ă’(port)"~X: socket.connect((hostname,port)) Ă‘Ă–ĂŹ Ă‚ĂŤ žŒ TCP ĂšUnix Â? socket âk Ă‚ĂŤ žŒ `{" Ăś Â?{aq" sock.listen(12) clientsocket, address = sock.accept() listen ÂĽ ĂŤĂŞÂ?²ÂŒ É  ÂŒĂŤ ĂŞ8"accetp ŸêÂˆÂŁÂ˜Â‡^uĂ?& socket ĂšuĂĽĂŤ žŒ Â?rĂ /ÂŒ"

§3.8.6 Ă‚xêâ send Ăšrecv ´Ê ä…À?1܊ 1. XJsend ¤þÂˆÂŁ {§@o¿›XĂŠÂ? äÂ…Ă€¼Ž²k \ux êâ" 2. ÂŚ+send ¤þˆ£§@oĂ˜ÂżÂ›Xux . "ÂŚ ÂˆÂŁÂŠLÂŤux Ăľ ê⧠´Ă˜Â˜½Ăš\ux êâÂŒ ˜—"‡ŽÑuxĂ‘ §7L^aqeÂĄ “è" annCharles@tom.com

1141Â?, 208Â?

Python ÆS)P


n Python ~^ ÂŹ totalsent = 0 while totalsent < MSGLEN: sent = self.sock.send(msg[totalsent:]) if sent == 0: raise RuntimeError, \\ "socket connection broken" totalsent = totalsent + sent „Ă?§python ÂĽ sendall ŸêÂŒÂą ¤Ú‡þU" 3. XJsend ÂˆÂŁ0 §LÂŤĂŠÂ?Ăš\`§â€œ¡Ž²'4 Éêâ ĂľU§Ă˜U 2 Ă‚\ êâ â€?" ´\„kÂŒU Ă‚ĂŠÂ? êâ" 4. XJrecv ¤þÂˆÂŁ {§@o¿›X\Ă‚ ê⧠´Ă˜Â˜½ÊÂ?send Ÿêux Ăľ êâ\Ă’U Ă‚Ăľ "¯¢Þ§TCP socket U y Ă‚ êâ ^SÚÊÂ? ux ^S˜—§ ´Ă˜Â˜½U y\Ă‚v "kÂŒU\Ă‚ êâ´ÊÂ?Ăźgu x êâ§Â?kÂŒU\Ă‚ êâÂ?´ÊÂ?uxêâ Â˜ĂœŠ" 5. XJrecv ÂˆÂŁ0 §LÂŤĂŠÂ?Ăš\`§â€œ¡Ž²'4uxêâ ĂľU§Ă˜U 2‰\u xêâ â€?" ´\„kÂŒU‰ÊÂ? uxêâ" \ÚÊÂ?ĂŻĂĄÂ˜Â‡TCP ĂŤ ƒ §Ă’ĂŻĂĄ ˜‡V• DĂ‘Ă? §Ă’”k߇+ f§ŠOLß‡Â?•\ux‰ÊÂ?§ĂšĂŠÂ?ux‰\ Ă? " <Ă‘Â˜Â‡+f5w§+f ßÞkuxÂ?Ăš ÉÂ?§uxÂ?Ă˜ä/•+fpÂĄ5Y§Â? N^Ă—§Â?N@¼§Â?N^ §Â?N^ "XJ^Ă— {§@oÂŒU+f Yá §Â˜Ă˜e @oĂľ Y§Ă’/e˜Œ§Â? ˜Œ3Ă—p§XJ\‡” Ăœ/\ {§Ă’ Â˜ÂŹ § Â?+f Y6e §eg2/" XJsend ÂˆÂŁ0 {§LÂŤ Ă‚Â?r+fĂ—4 " Ă‚Â?3+f ,Â˜Ăž 6Ă‘5 Y§Â?N^Ă—§Â?N@¼§Â?N^ §Â?N^ § ´ Ă‘5 Y§Ă˜Â˜½´uxĂ Ă“Â˜ÂĽS Y§XJ\^Ă— Y§kÂŒU Ă‚ĂŠÂ?Êþ¼ Y"XJ\^ÂĽ §@oÂŒU Ă‚ Â?´ÊÂ?ux Â˜Ă—YÂĽ Â˜ĂœŠ" XJrecv ÂˆÂŁ0 {§LÂŤuxÂ?r+fĂ—4 " ÂŒU?Ă› 'Â’Ă‘´Â– " Ăš ‘5 ÂŻKĂ’´§XĂ›½Ă‚VÂ? uxĂš Ă‚^S§ĂšuxĂľ Ăš Ă‚Ăľ "Â?Ă’ ´`§Â&#x;ožÿ\`{§Â&#x;ožÿ¡`{§ÂˆÂ‡ `{ žm´þ QÂş

§3.8.7 ämĂŤ ^close ŸêÂŒ¹ämĂŤ §'4socket "Ú´{ĂźZy Â?{" Â?ÂŒÂą^shutdown(how) Ÿê"ÂŚ Ă‚Â˜Â‡ꐤ^uÂ?²N ämĂŤ " annCharles@tom.com

1142Â?, 208Â?

Python ÆS)P


§3.8 socket ?§ 1. how = 0 Läm Ă‚Ă? "Â?Ă’´XJĂŠÂ?N^send uxêâ {§ÂˆÂŁ0 LÂŤ Ă˜U 2uxêâ §ÊÂ?Ž²äm Ă‚Ă? " ´shutdown(0) ƒ §Â„ÂŒÂąu xêâ §ÊÂ?Â?´ÂŒUĂ‚ êâ " § Âżg´wŠÊÂ?§¡Ă˜2 Ă‚êâ §O2ux " 2. how = 1 LämuxĂ? "Â?Ă’´XJĂŠÂ?N^recv uxêâ {§ÂˆÂŁ0 LÂŤ Ă˜U 2 Ă‚êâ §ÊÂ?Ž²äm uxĂ? " ´shutdown(1) ƒ §Â„ÂŒÂą Ă‚ê⠧ŒUĂ‚ ĂŠÂ? uxêâ " § Âżg´wŠÊÂ?§¡Ă˜2uxêâ §O2 Ă‚ " 3. how=3 LÓžämuxĂš Ă‚Ă? " XJĂ?&ĂŤ ÂĽ ˜Â?3Ă?&L§¼Â?ÂŽ Ă‚ê⧠Ă˜uxêâ§@oÂŚÂŒU3ĂŤ ffĂŻĂĄÂƒ §Ă’'4uxĂ? " Â?‡Ă?& Ƽ5½ ˜Â?Ă˜Uuxêâ§@oÂŚĂ’AT'4uxĂ? " XJrecv ŸêÂˆÂŁ0 §LÂŤĂŠÂ?'4 uxĂ? §@oĂ’AT'4 Ă‚Ă? " XJsend ŸêÂˆÂŁ0 §LÂŤĂŠÂ?'4 Ă‚Ă? §@oĂ’AT'4uxĂ? " XJuxĂ? Ăš Ă‚Ă? Ă‘'4 §@oĂ’ATs.close() " XJ\‰ Ă˜[—§Â† s.close() Â?1" ^ socket ˜½Â‡'4§Œ+socket module ÂŹgĂ„'4Ă˜2ÂŚ^ socket § ´3 §S¼²w '4˜‡socket Â’½´Â˜Â‡Ă?ĂŒÂż"

§3.8.8 ٌ9Ă?Ÿê ~f: >>> import socket >>> socket.gethostname() ’charles.home.com.cn’ >>> socket.gethostbyname(socket.gethostname()) ’192.168.200.18’ >>> socket.gethostbyname_ex("www.sohu.com") (’pagegrp1.sohu.com’, [’www.sohu.com’], [’61.135.150.67’, ’61.135.150.69’, ’61.135.150.74’, ’61.135.150.75’, ’61.135.131.73’, ’61.135.131.180’, ’61.135.131.183’, ’61.135.132.172’, ’61.135.132.173’, ’61.135.132.174’, ’61.135.132.176’, ’61.135.133.109’, ’61.135.145.47’, ’61.135.150.65’, ’61.135.150.66’]) >>> socket.gethostbyname("www.sohu.com") annCharles@tom.com

1143Â?, 208Â?

Python ÆS)P


n Python ~^ ÂŹ ’61.135.131.180’ >>> socket.gethostbyaddr("127.0.0.1") (’localhost.localdomain’, [’localhost’], [’127.0.0.1’]) >>> socket.getservbyname("http",’tcp’) 80 >>> socket.getservbyname("mail",’tcp’) 25 >>> socket.getservbyname("smtp",’tcp’) 25 >>> socket.getservbyname("pop3",’tcp’) 110 >>> socket.getservbyname("ftp",’tcp’) 21 >>> socket.getservbyname("tftp",’udp’) 69 >>> socket.getservbyname("time",’udp’) 37 >>> socket.getprotobyname("udp") 17 >>> socket.getprotobyname("tcp") 6 >>> socket.getprotobyname("icmp") 1 >>> socket.getprotobyname("sctp") 132 gethostname ÂŒÂą c ĂŒĂ…ϴ" gethostbynameÂŒÂąÂŠâĂŒĂ…ϴ ĂŒĂ… IP /ÂŒ" gethostbyname_ex ÂŒÂąÂŠâĂŒĂ…ϴ ĂŒĂ… ¤kϴ&E"ÂŚÂˆÂŁÂ˜Â‡tuple" (hostname,hostnamealiaselist,ipaddrlist) Â?škĂŒĂ…œ¥§ĂŒĂ…OÂśL§Â˜Â‡ĂŒĂ…ÂŒUkþ‡OϤĂŒĂ… IP /ÂŒL§Â˜Â‡ĂŒĂ… ÂŒÂąkþ‡IP /ÂŒ" gethostbyaddr ÂŒÂąÂŠâIP /ÂŒ ĂŒĂ… ¤kϴ&E" getservbyname ÂŒÂąÂŠâĂ‘Ă– œ¥§ ĂŠA Ă Â?Ă’"I‡Â?½´TCP Ƅ ´UDP Æ" annCharles@tom.com

1144Â?, 208Â?

Python ÆS)P


§3.8 socket ?§ Ÿêœ¥

ŠÂ

htons(sint ) ntohs(sint ) htonl(lint ) ntohl(lint )

rĂĄ .lĂŒĂ…^SCÂ? ä^S rĂĄ .l ä^SCÂ?ĂŒĂ…^S r .lĂŒĂ…^SCÂ? ä^S r .l ä^SCÂ?ĂŒĂ…^S

L 3.8-8: ^u=†i!^S Ÿê getprotobyname ÂŒÂąÂŠâ Æ œ¥§ ĂŠA Æ Ă’è§ÚÂ‡ÂŠÂŒÂąD4‰M ĂŻsocket ž socket(domain,type,protocol) ÂĽ 11n‡Íêprotocol " eÂĄ Ÿê^u=†i!^S"XL3.8-8" Ă™¼§h “LĂŒĂ…§n “L ä§to “L=†§s “LĂĄ .§l “L ."

§3.8.9

TCP ĂšUDP ÂŤO

TCP ´¥Â•ĂŤ "UPD ´¥Â•ÂšĂŤ "TCP Ҕ‹>{§Ă?&ƒck‡ïåÍ §X§à Ă…§ĂƒĂ’§ $§ÊÂ? f"Ă?& .ƒ ‡ämĂŤ "UDP ҔM&§Ă?& ƒcĂ˜^ĂŻĂĄĂŤ §r#Â?3&¾¼§3&¾Þ Ă?/Π uxĂ’ÂŒÂą " ' XL3.8-9: TCP ÂŹ yĂ‚u^S´Â˜Â— §UDP KĂ˜§uà êâkÂŒU

uk–"

TCP ÂŹ yÂ?Ă˜ÂŹÂżÂ”§XJsend ¤þˆ£§@oĂ’Â˜½ ˆ ĂŠÂ? ä…À S§ÊÂ?Â?‡N^recv Ă’Â˜½ uĂ ux êâ"UDP Ă’Ă˜§Â˜Â„Âœše§sendto ²~Ă‘U¤þ § ´Ă˜ yĂŠÂ?˜½Ă‚ §Â?kĂ?LĂž Æ y "˜„ Â?{Ă’´ Â?z˜‡ux êâÂ??Ă’§ÊÂ?Ă‚ Ă’ÂŁx˜‡Â?A§`¡Ă‚ §XJ3˜½ žmT Svk ĂŠÂ? Â?A§Ă’­#ux§­#uxN gƒ §Â„´Â”}§K@Â?ux”}"T Ă’´Â‡ÂžÂžm§Â˜Â„´N Ÿê§Â?N OÂŒ OÂŒ§ …„‡O\Â˜Â‡Â‘Ă… £Þ§Â“ ÂŽĂľÂ‡ĂŒĂ…Ă“ÂžÂ•Ă“Â˜Â‡ĂŒĂ…ux" TCP yux êâĂš Ă‚ êâ Ă˜ÂŹk­E§UDP Ă’Ă˜§uà êâÂŒUÂŹÂ˜ uþ–"Ú´Ă?Â?UDP êâÂ?²Lþ‡´dĂŹÂƒ §êâÂ?3 ä¼ )­E Â?" 3TCP ¼§Â˜½kClient ĂšServer ƒŠ§Ă?Â?Server Â‡ĂŻĂĄÂ˜Â‡AĂ? socket ^ui fĂš Ă‚client ĂŤ žΤÂˆÂŁÂ˜Â‡^uĂ‚uêâ socket ƒ §Client ĂšServer 3´Ê Ă‚u¢N"3UDP ¼§vkServer ĂšClient ƒŠ§¤k ĂŒĂ…ĂŻĂĄ socket ƒ §Ă’ ÂŒÂąĂ‚uêâ §Ă“Â˜Â‡socket ÂŒÂą^5 Ă‚Ă˜Ă“ĂŒĂ… UDP êâ§Ă“˜‡socket Â?ÂŒÂą Â‰Ă˜Ă“ ĂŒĂ…uxêâ" annCharles@tom.com

1145Â?, 208Â?

Python ÆS)P


n Python ~^ ¬

Ï& c´Äïáë ´Ä y  ^S ´Ä y  ج ¿ ´Ä y  ج­ E Ï& ª X J Ñ Ö ì n rÑÖ§ÑÖìà socket êþ ´Äk6þ Âuêâ¦^ ¼ê ´Ä¦^listen,accept ¢ 5

TCP

UDP

´ ´ ´

Ä Ä Ä

´

Ä

Client/Server n+1

顪 1

´ send/recv ´

Ä sendto/recvfrom Ä Ð

L 3.8-9: TCP ÚUDP «O 6þ ¿gÒ´`§XJÂà ä À«÷ §Òw é §é Ò¬ú:u xêâ§XJ §Ò¬w é ±¯:uxêâ"TCP ±§ ´UDP vkù«Å "TCP 3Ï& L§¥§z Ñk SÒ§z ѣ é (@â@ u x¤õ"

§3.8.10 'uTCP ÑÖì {K ÑÖìà É^r ë ¦§ ?nÂuê⧠k±e {" 1. ÑÖìfork f?§§3f?§¥?nÚé Ï&"I?§UY?nÙ¦^r ë ¦" 2. ÑÖìMï §§^Õá §?nÚé Ï&" 3. ÑÖì^select ¼ê§ÓÎsocket § Ò´`§3Âuêâ c§kwwsocket ´Ø ´ ±Âuêâ" 4. ¦^ {l¼ê§ Ò´`§accept send ¼ê¬á= £" e¡ ~f§Ñ´¢y {ü ÑÖì§Ò´l^r=p Âêâ§, âH¬ ^r" annCharles@tom.com

1146 , 208

u  ê

Python ÆS)P


§3.8 socket ?§ Õá?§ ~f: #/usr/bin/env python # echo.server.fork.py # simpleserver.py import socket,sys,os clients=[] def handledata(s): data = s.recv(1024) while data: try: s.send(data) data = s.recv(1024) except: sys.exit(0) def main(): s = socket.socket(socket.AF_INET,socket.SOCK_STREAM) s.bind((socket.gethostname(),8080)) s.listen(10) while 1: clientsocket,clientaddress = s.accept(); pid = os.fork() if pid==0: # child process # close the server socket . # because the child process should not # care about the accept the connect request s.close() handledata(clientsocket) else: # this is parent process # close the client socket # because the parent should not # care about sending/receiving data clientsocket.close() if __name__ == "__main__" : main() annCharles@tom.com

1147 , 208

Python ÆS)P


n Python ~^ ÂŹ ~f¼§Ă‘Ă–ĂŹ ^r ĂŤ ÂžΤ Ă‰ĂŤ § )˜‡f?§"fork ŸêÂ˜gN^ ĂźgÂˆÂŁ"ڞ§ß‡A Ă“ ?§3S ÂĽ$1"Ă˜Ă“Âƒ?3u§f?§ÂˆÂŁ pid ´0 §I?§ÂˆÂŁ ´f?§ ID " f?§Ă˜I‡3?nĂŤ žŒ§¤¹'4s " ?nĂ‚uêâ" I?§Ă˜I‡?nĂ‚uê⧤¹'4clientsocket § UYaccept e˜‡^r ĂŤ žŒ" Â?Â&#x;o‡'4socket §Ă?Â?If?§A ˜ §ŒÂ‚ Â?Ă“ ‹m socket "¤¹ Â? ;Â?Ă€⧠Ă?'4˜ Ă˜^ "f?§'4s §Ă˜^Ăş%§sĂ™¢Â„vkĂ˝ Ă­Ă˜ K§Ă?Â?„kI?§3^" f?§XJÉ~òĂ‘ §Ă˜ÂŹKÂ?I?§ $1"If?§ÂƒmĂ˜2 Â?ê⧌‚ƒ m^Ă?& {§Ă’7LÂŚ^Ă™§ ?§mĂ?& Â?{" Õ傧 ~f: #/usr/bin/env python # echo.server.thread.py import socket,sys,os,thread clients=[] def handledata(s): global clients data = s.recv(1024) while data: try: for i in clients: i.send(data) data = s.recv(1024) except: sys.exit(0) def main(): s = socket.socket(socket.AF_INET,socket.SOCK_STREAM) s.bind((socket.gethostname(),8080)) s.listen(10) while 1: clientsocket,clientaddress = s.accept(); clients.append(clientsocket) annCharles@tom.com

1148Â?, 208Â?

Python ÆS)P


§3.8 socket ?§ thread.start_new_thread(handledata,(clientsocket,)) if __name__ == "__main__": main() ĂŠN´ O\˜‡*Ă?ĂľU§Ă‘Ă–ĂŹĂ˜Â?r^ru êâHÂŁ § ´H£‰¤k ĂŤ ^r§Ă’”3mÂŹÂ˜ " ^‚§ Â?ª§Â?k˜‡?§ 3§z˜‡?§ Â?Ă“Â˜Â‡S ˜m§¤¹Ê^N´¢ yĂ˜Ă“?§Âƒm Ă?&§Ă“žÂ?ĂŠN´ )–¯Àâ§I‡c[ O§O\&Ă’Ăž ? n"Þ¥ ~f¼§k˜‡ ÂŻK§ĂŒÂ‚§3V\˜‡socket clients ÂĽ žÿ§¤k f‚§Ă‘3ÂŒUÂŚ^clients §kÂŒUĂ€â" Â…§?Ă›Â˜Â‡Â‚§N^ sys.exit ½Ü )É~ {§@o ‡ÑÖÏÒ K " ÂĄ ٌÂ?{Â?˜ §Ă?Â?Œ‚Ñ´^˜‡‚§?n " Ă“ĂŽ #/usr/bin/env python # echo.server.select.py import socket,sys,os,select clients=[] def handledata(s): data = s.recv(1024) for i in clients: i.send(data) def main(): s = socket.socket(socket.AF_INET,socket.SOCK_STREAM) s.bind((socket.gethostname(),8080)) s.listen(10) while 1: rlist , wlist,xlist = select.select([s,],[],[],0) if rlist: # ok, now a new client comming clientsocket,clientaddress = s.accept(); clients.append(clientsocket) rlist , wlist,xlist = select.select(clients,[],[],0) if rlist: for i in rlist: handledata(i) if __name__ == "__main__": main() annCharles@tom.com

1149Â?, 208Â?

Python ÆS)P


n Python ~^ ÂŹ ڇ~f¼§'Â…3uselect Ÿê ^{§Œ^ýÿ´Â˜|ʖ´Ă„ÂŒÂąĂ– "Ă‘\ d4‡Í꧊O´ÿà ´Ă„ÂŒĂ– ʖL§ÂŒ ʖL§ÿà ´Ă„kÉ~ ʖL§Ăš ˜‡ –žm" ÂˆÂŁ žÿ§ÂˆÂŁÂŒĂ–ʖ L§ÂŒ ʖ L§Ăšu) É~ ʖL" s ÂŒĂ– žÿ§LÂŤÂŒÂąN^accept Ÿê " clientsocket ÂŒĂ– žÿ§LÂŤÂŒÂąN^recv Ÿê " du¤k ŠÊÑ´^S‰1 §vkÂż1 §S§Ă˜ÂŹĂ‘y Â?Ă€â ÂŻK" Â…ÂŒ [Ăş^Ă“Â˜Â‡?§ S ˜m§ÂƒpĂ?&Â?Ă˜¤¯K" ´XJhandledata Ÿê ?ns ĂŠĂˆ žm§½ÜkĂŒÂ‚ §@oĂ’ÂŹ{ÂŽ Ă‚ # ĂŤ žΤÚٌ^r êâ?n" O žÿÂ?‡ %" e‡?nƒ' ĂœŠ

§3.9 Ă‚e‡ §3.10 POP3 Æ0 §3.10.1 ˜‡{Ăź ~f POP3(Post Office Protocol - Version 3) ڇ Æ^u½Ă‚Â?rĂ XĂ›lĂ‘Ă–ĂŹĂ Ă‚ e‡" Ă?~§POP3 Ă‘Ă–ĂŹ3110 Ă Â?ifTCP ĂŤ žŒ"Â?rĂ uĂĽĂŤ žΤÚÑÖÏ ĂŻĂĄTCP ĂŤ " e¥´Â˜Â‡~f: S: <wait for connection on TCP port 110> C: <open connection> S: +OK POP3 server ready <1896.697170952@dbc.mtview.ca.us> C: APOP mrose c4c9334bac560ecc979e58001b3e22fb S: +OK mrose’s maildrop has 2 messages (320 octets) C: STAT S: +OK 2 320 C: LIST S: +OK 2 messages (320 octets) S: 1 120 S: 2 200 S: . C: RETR 1 S: +OK 120 octets annCharles@tom.com

1150Â?, 208Â?

Python ÆS)P


§3.10 POP3 Æ0 S: S: C: S: C: S: S: S: C: S: C: S: C: S:

<the POP3 server sends message 1> . DELE 1 +OK message 1 deleted RETR 2 +OK 200 octets <the POP3 server sends message 2> . DELE 2 +OK message 2 deleted QUIT +OK dewey POP3 server signing off (maildrop empty) <close connection> <wait for next connection>

§3.10.2 ÂŚ^POP3 Æ Ă‚e‡ Ă‘Ă–ĂŹĂ‚ ĂŤ žŒ S:

§uxÂ˜Â‡ÂŻĂżÂŠ"

+OK POP3 server ready <1896.697170952@dbc.mtview.ca.us> ,

§Â?rĂ Ă’ux¡-§Ă‘Ă–ĂŹux¡- Â?A"z˜‡¡-Ă‘´Â?k˜1"

˜1 ½Ă‚Ă’´¹CRLF (ÂŁÂ?†1) (— ˜ãêâ" z‡¡-k˜‡'Â…i(Keyword)§L¡- œ¥§´4 ‡i1§XLIST, STAT "k ¡-‘kꐤ^˜‡˜‚ŠmĂŤĂŞĂš¡-" ĂŠuk ¡-§Ă‘Ă–ĂŹ Â?Ašk˜1"1˜1 1˜‡cÂŒU´â€œ+OKâ€? ½Ü“ERRâ€? ŠOLÂŤ ~ÚÉ~ Âœš"

§3.10.3 Ăľ1Â?A ?n k˜ ¡-§Ă‘Ă–ĂŹ Â?AškĂľ1"Â?A (ĂĽI“´==Â?šÂ˜Â‡:2 §â€œ.â€? 1"XJê⼚kÂąâ€œ.â€? mĂž 1§@oĂ’rڇ:UÂ?߇:“..â€? § Ă‚Ă - Ăš 1§Ă’ Œ´êâ§rÂŚÂĄEL5Ă’1 " uxĂ ?nXe: for line in uxêâ ¤k1: if line.find(".")==0) : #Âą . mĂž line="."+line ux line 2

=Š¼ ĂŠĂ’

annCharles@tom.com

1151Â?, 208Â?

Python ÆS)P


n Python ~^ ¬ # vkêâ

ux ".\r\n" Âà ?nXeµ for line in  êâ ¤k1: if line == ".\r\n" : break # Â(å if line.find("..")==0) : #± . mÞ line= line[1:] # K . V\ line Aêâ¥"

§3.10.4 POP3Ï&L§¥ G ràÚÑÖìàÏ&L§¥kn G µ AUTHORIZATION ïáTCP ë

§?\TG "ÑÖì ràux¯ÿ "

TRANSACTION ràJø^r¶¡Ú 觤õ ¹ §ÑÖìàé rà e § r© ] "3ù G ¥§ rÚÑÖìàm© p·-" TRANSACTION ÑÖì QUIT ·- §?\TG §3ù G ¥§º r © ] § ¤^rJ ö §'4TCP ë " 3AUTHORIZATION G §kü«Jø èÚ^r¶¡ ª" 1. ¦^USER ÚPASS ·- |Ü"

2. üÕ¦^APOP ·-"

§3.10.5 POP3¥ ·e¡0 eÌ ·-: 1. USER -

ª: USER name ëê: name ^u ½^r¶¡ ^å: 3AUTHORIZATION G ¥§Ï ÑÖì^r¶¡" A:

annCharles@tom.com

1152 , 208

Python ÆS)P


§3.10 POP3 Æ0 +OK name is a valid mailbox -ERR never heard of mailbox name - ~f: C: USER frated S: -ERR sorry, no mailbox for frated here ... C: USER mrose S: +OK mrose is a real hoopy frood 2. PASS -

‚ª: PASS string ĂŤĂŞ: string ^uÂ?½^r—è ^ĂĽ: 3AUTHORIZATION G ¼§Ă? Ă‘Ă–ĂŹ^r—è" Â?A: +OK maildrop locked and ready -ERR invalid password -ERR unable to lock maildrop

- ~f: C: USER mrose S: +OK mrose is a real hoopy frood C: PASS secret S: -ERR maildrop already locked ... C: USER mrose S: +OK mrose is a real hoopy frood C: PASS secret S: +OK mrose’s maildrop has 2 messages (320 octets) 3. APOP - ‚ª: APOP username digest - ĂŤĂŞ: username ^uJø^rϴ"digest ^uJø\— —è - ^ĂĽ: 3AUTHORIZATION G ¼§Ă? Ă‘Ă–ĂŹ^rϴڗè" XJÂŚ^USER ĂšPASS |Ăœ§@o^rϴڗèŒ^²Š3 ä¼D4§ Ăš kS ۇ"APOP ¡-Ă’´Â? Â?\S Â˜ÂŤ@yś" annCharles@tom.com

1153Â?, 208Â?

Python ÆS)P


n Python ~^ ÂŹ X J ˜ ‡ Ă‘ Ă– ĂŹ | ÂąAPOP ¡ - § @ o 3 ÂŻ Ăż Š ÂĽ Â? š ˜ ‡ i ĂŽ G § ‰timestamp §3Unix XĂš¼§Â˜Â„´eÂĄ ‚ª <process-ID.clock@hostname> Ù¼process-ID ´?§Ă’§clock ´Â?ĂŒĂ…$1 žm§hostname ´ĂŒĂ… Â?Âś"Ăš z˜g š§Ă‘ÂŹkĂ˜Â˜ timestamp " rtimestamp(Â?)k)Ă’) ڗèĂœ3Â˜ĂĽ\—§digest Ă’´\— —Š§\ —Ž{´RFC 1321 ÂĽ MD5 "digest ´Â˜Â‡šk16‡i! iĂŽG§´Â˜Â‡ĂŠ ÂŒ ĂŞ ›8?›LÂŤ" - Â?A: +OK maildrop locked and ready -ERR permission denied - ~f: S: +OK POP3 server ready <1896.697170952@dbc.mtview.ca.us> C: APOP mrose c4c9334bac560ecc979e58001b3e22fb S: +OK maildrop has 1 message (369 octets) 3ڇ~f¼§XJ—è´tanstaaf @o‡\— iĂŽG´: <1896.697170952@dbc.mtview.ca.us>tanstaaf \— ) —Š´¾ c4c9334bac560ecc979e58001b3e22fb 4. STAT -

‚ª: STAT ĂŤĂŞ: Ăƒ ^ĂĽ: e‡¼ e‡êÞ Â?A: +OK nn mm

Ù¼nn LÂŤe‡‡ê§mm LÂŤe‡¼¤ke‡ ¤Ă“ i!ĂŞ" - ~f: C: STAT S: +OK 2 320 ڇe‡¼kß¾&§ Ă“320 ‡i!" 5. LIST annCharles@tom.com

1154Â?, 208Â?

Python ÆS)P


§3.10 POP3 Æ0 - ‚ª: LIST [msg] - ĂŤĂŞ: msg Íê´ÂŒĂ€ §XJvkJøÚ‡ꐤ@oT¡- Â?AÂ?šþ 1§z˜1Â?²Â˜Â‡e‡ ÂŒ "XJJø ڇꐤ@oĂ’ÂˆÂŁÂ?½e‡ ÂŒ " - ^ĂĽ: we‡ ÂŒ - Â?A: +OK scan listing follows -ERR no such message - ~f: C: LIST S: +OK 2 messages (320 octets) S: 1 120 S: 2 200 S: . ... C: LIST 2 S: +OK 2 200 ... C: LIST 3 S: -ERR no such message, only 2 messages in maildrop Ăľ1Â?A¼§Â?Â?šâ€œ.â€? 1LÂŤÂ?A(ĂĽ"z˜1§Â?šß‡êi§cÂĄ e Â‡Ă’è§ ÂĄ ´e‡Œ §¹i!Â?ß " 6. RETR -

‚ª: RETR msg ĂŤĂŞ: msg Â?²Â‡ Ă‚=Âľe‡" ^ĂĽ: Ă‚e‡" Â?A: +OK message follows -ERR no such message

XJÂˆÂŁ ~§^Ăľ1LÂŤe‡ SN"Ăľ1Â?A¼§Â?Â?šâ€œ.â€? 1LÂŤÂ?A (ĂĽ"ê⼚kÂąâ€œ.â€? mĂž 1§3mĂž \˜‡“.â€? § Ă‚Ă Ă‚ Âąâ€œ.â€? mĂž 1§ T1Ă˜´Â?Â?šâ€œ.â€? 1§@oĂ­Ă˜mĂž “.â€?" - ~f: annCharles@tom.com

1155Â?, 208Â?

Python ÆS)P


n Python ~^ ÂŹ C: S: S: S:

RETR 1 +OK 120 octets <the POP3 server sends the entire message here> .

7. DELE - ‚ª: DELE msg - ĂŤĂŞ: msg Â?½Â‡Ă­Ă˜e‡ Ă’è" - ^ĂĽ: ‰e‡e‡‹ÞíĂ˜IP§XJ ÂĄ ¡-§3¢ĂšTe‡§@oĂ’ĂŠĂ˜ " ´e‡vkĂ˝ Ă­Ă˜§Â?kĂ?LQUIT ¡-§ ~?\ UPDATE G §e‡⏠íĂ˜" - Â?A: +OK message deleted -ERR no such message - ~f: C: DELE 1 S: +OK message 1 deleted ... C: DELE 2 S: -ERR message 2 already deleted 8. NOOP -

‚ª: NOOP ĂŤĂŞ: Ăƒ" ^ĂĽ: Â˜ĂśÂŠ" Â?A: +OK

- ~f: C: NOOP S: +OK 9. RSET - ‚ª: RSET - ĂŤĂŞ: Ăƒ" annCharles@tom.com

1156Â?, 208Â?

Python ÆS)P


§3.10 POP3 Æ0 - ^ĂĽ: XJe‡ DELE ¡-‹Þ Ă­Ă˜IP§@oĂ’ KIP§Â?Ă’´¥E¤ kĂ­Ă˜ e‡" - Â?A: +OK - ~f: C: RSET S: +OK maildrop has 2 messages (320 octets) 10. QUIT - ‚ª: QUIT - ĂŤĂŞ: Ăƒ" - ^ĂĽ: ?\ UPDATE G §Ă‘Ă–ĂŹ ڇ¡-ƒ §ý Ă­Ă˜¤k‘kĂ­ Ă˜IP e‡§ºÂ˜Â?Â?rà ž ] "'4TCP ĂŤ " - Â?A: +OK -ERR some deleted messages not removed - ~f: C: QUIT S: +OK dewey POP3 server signing off (maildrop empty) ... C: QUIT S: +OK dewey POP3 server signing off (2 messages left) 11. TOP - ‚ª: TOP msg n - ĂŤĂŞ: msg Â?²e‡ Ă’è§n Â?²1ĂŞ" - ^ĂĽ: ĂšRETR aq§ ´==Ă‚ e‡ Š¼ n 1§Ă˜Â?)e‡Þ"e‡Þ Ăše‡ Š^˜1ŠÂ…" - Â?A: +OK top of message follows -ERR no such message - ~f: C: TOP 1 10 S: +OK annCharles@tom.com

1157Â?, 208Â?

Python ÆS)P


n Python ~^ ÂŹ

S: <the POP3 server sends the headers of the message, a blank line, and the first 10 lines of the body of the message> S: . ... C: TOP 100 3 S: -ERR no such message 12. UIDL - ‚ª: UIDL [msg] - ĂŤĂŞ: msg ´ÂŒĂ€ §Â?²e‡Òè" - ^ĂĽ: ĂšLIST ¡-aq§ ´ÂˆÂŁ Ă˜´e‡ ÂŒ § ´e‡ unique-id ˜ ‡Â?˜ IÂŁ" unique-id ´Â˜Â‡iĂŽG§ ÂŒ Ă?´70 §iĂŽÂŒ¹´0x21–0x7E ÂĽ ?ÂżÂ˜ ‡"ڇunique-id ´z˜‡e‡Â?˜ §zg šŒĂ‘Ă˜ÂŹC" - Â?A: +OK unique-id listing follows -ERR no such message - ~f: C: UIDL S: +OK S: 1 whqtswO00WBw418f9t5JxYwZ S: 2 QhdPYR:00WBw1Ph7x7 S: . ... C: UIDL 2 S: +OK 2 QhdPYR:00WBw1Ph7x7 ... C: UIDL 3 S: -ERR no such message, only 2 messages in maildrop

§3.11 ^poplib ÂŹĂ‚ e‡ #!/usr/bin/env python # pop3example1.py import sys,os,poplib annCharles@tom.com

1158Â?, 208Â?

Python ÆS)P


§3.11 ^poplib ÂŹĂ‚ e‡ def main(): SERVER = "your.email.pop3.server" USER = "username" PASSWORD = "password" # connect to server server = poplib.POP3(SERVER) # login server.user(USER) server.pass_(PASSWORD) # list items on server resp, items, octets = server.list() for item in items: id,size = items.split(" ") # download a random message resp, text, octets = server.retr(id) print "---------------mail No.%d---------------------" print text.join("\n") # be careful, your email will be deleted # server.dele(id) server.quit() if __name__ == "__main__": main() `²¾ 1. poplib.POP ÂˆÂŁÂ˜Â‡server ʖ§3POP Ă?ŠzŸê¼§Œü•ÑÖÏïåÍ §¿Â… Ă‘Ă–ĂŹux ¯ÿŠ"XJĂ˜UĂŻĂĄĂŤ §@oĂ’ Ă‘socket.error É~" 2. server.user Ăšserver.pass_ ¡-§Â•Ă‘Ă–ĂŹ@y š"XJ šĂ˜¤þ§@o Ă‘poplib.error_proto É~"XJ˜‡¡- Â?AĂ˜´¹â€œ+â€? mĂž §@oڇ¡ -Ă‘ÂŹ Ă‘Ăš É~" 3. server.list e‡ L"resp ´Â?AÂĽ 1˜1"items ´Â˜Â‡list §^SÂ?š Ăľ1Â?AÂĽ z˜1"octets ´þ1Â?AÂĽ i!‡ê"Â…´þ1Â?A ¡-§ÂˆÂŁ Ă‘´aq " 4. server.retr ^5 Ă‚e‡"server.dele ^5Ă­Ă˜e‡"Ă­Ă˜eÂ‡ĂšÂ˜1§ 5Âş K §Ă?Â?“è¼Â?´r Ă‚ e‡print Ă‘5§¿vk ;§¤¹Â„Ă˜Ăœ´íĂ˜e ‡" annCharles@tom.com

1159Â?, 208Â?

Python ÆS)P


n Python ~^  Ÿêœ¥

ÂŁĂŁ

p=server(servername,portnumber) p.user(strUser) p.pass (strPass) p.stat()

ĂŻĂĄĂŤ "ÂˆÂŁĂŠÂ–p§|ÂąeÂĄ Ÿê" ux^rϴ"strUser ´iĂŽG" ux—è"strPass ´iĂŽG" e‡G "ÂˆÂŁÂ˜Â‡tuple §šk߇ ĂŞi§L²e‡‡ê§Ăše‡Œ " e‡,Â˜Âľe‡ ÂŒ "XJÂ? ½which @ o ˆ ÂŁ ˜ ‡ Ăź 1 Â? A § X J Ă˜ Â?½§ÂˆÂŁĂľ1Â?A" Ă‚ e‡"ÂˆÂŁÂ˜Â‡tuple §škn‡ ƒ§ ŠO´þ1Â?AÂĽ 1˜1§z˜1ê⧠Ăšêâ ÂŒ " Ă­Ă˜e‡"ÂˆÂŁĂź1Â?A" Â˜ĂśÂŠ"ÂˆÂŁĂź1Â?A" ÂĄEĂ­Ă˜e‡"ÂˆÂŁĂź1Â?A" ^APOP ¡-@y" Ă‚ e‡Þ§Ăšretr ÂˆÂŁaq" Ăšlist aq§ÂˆÂŁe‡ Â?˜IÂŁ"

p.list(which=None)

p.retr(msg)

p.dele(msg) p.noop(msg) p.rset() p.apop(username,password) p.top(which,howmuch) p.uidl(which=None)

L 3.11-10: poplib ¡-o( lڇ~fÂŒÂąw §poplib ÂĽ ¤k¡-A Ă‘ĂšPOP3 Æ5½ ƒ˜—" poplib ¡-o(XL3.11-10

§3.12 SMTP Æ0 SMTP( Simple Mail Transfer Protocol) ´{Ăźe‡DĂ‘ Æ"ÂŚÂżĂ˜Â?6†. D Ă‘ ƧÂ?‡Œk˜‡Œ‚ 6Ă? (stream channel)"SMTP ÂŚ^ DĂ‘ Ƽ§A^ 2Â? ´TCP Æ" SMTP Â˜Â‡ĂŒÂ‡ÂŠ^Ă’´|^DĂ‘Ă‘Ă–(transport service) Jø ?§mĂ?&‚ ¸(interprocess communication environment,IPCE) 3ĂŒĂ…Âƒm=u(relay) e‡"

§3.12.1 SMTP ˜‡~f S: R: S: R: S:

HELO Alpha.ARPA 255 Beta.ARPA welcome MAIL FROM:<Smith@Alpha.ARPA> 250 OK RCPT TO:<Jones@Beta.ARPA>

annCharles@tom.com

1160Â?, 208Â?

Python ÆS)P


§3.12 SMTP Æ0 R: S: R: S: R: S: R: S: S: S: R:

250 OK RCPT TO:<Green@Beta.ARPA> 550 No such user here RCPT TO:<Brown@Beta.ARPA> 250 OK DATA 354 Start mail input; end with <CRLF>.<CRLF> Blah blah blah... ...etc. etc. etc. <CRLF>.<CRLF> 250 OK

S L ÂŤ u x Â? §R L ÂŤ Ă‚ Â? " Ăš ‡ ~ f ÂĽ § u x Â? e ‡ / ÂŒ ´<Smith@Alpha.ARPA> § Ă‚ e ‡ < k n ‡ § Š O ´<Jones@Beta.ARPA> §<Green@Beta.ARPA>§<Brown@Beta.ARPA> " SMTP uxÂ?Ăš Ă‚Â? p žÿ§uxÂ?ux˜‡¡-§ Ă‚Â?Ă‚ ¡-§?n §Â‰Ă‘ƒA Â?A" Ă‚Â?kn‡…À 1. forward path …À"^u ;forward path " forword path (c•´) ´Â?e‡ ÂˆĂ‚Â‡< ´"~X: @HOSTA.ARPA,@HOSTB.ARPA:Smith@HOSTC.ARPA L ÂŤ  ª Ă‚ ‡ < / ÂŒ ´Smith@HOSTC.ARPA § ´ & ‡ ‡ ˆ 8 / § 7 L ² LHOSTA.ARPA ĂšHOSTB.ARPA = u " k Ă’ c ÂĄ ĂŒ Ă… Âś ÂĄ § ^ Ă? Ă’ ŠÂ…§LÂŤe‡ ˆ ªĂ‚‡< ´"XJĂ˜Â?½=uĂŒĂ…§@oĂ’ ¤Smith@HOSTC.ARPA Ă’ÂŒÂą " 2. reverse path …À"^u ;reverse path " reverse path ( •´)´Â?eÂ‡ÂˆÂŁu‡< ´"ÂŚ LˆÂ?ÂŞĂšforward path ˜ "XJeÂ‡Ă˜U ˆu‡<§@ok )Â˜Â‡Â†Ă˜Ă? §Ú‡Ă? e‡á Xreverse path §ux‰u‡<" 3. êâ…À"^u ;ux e‡" k ¡-ÂŹĂŠn‡…ÀKÂ?" annCharles@tom.com

1161Â?, 208Â?

Python ÆS)P


n Python ~^ ¬

§3.12.2 uxe · p¯ÿ Ï&ë ffïá ÿ§ Âàux ¯ÿ "~Xµ 220 <SP> USC-ISIF.ARPA <SP> Service ready <CRLF> SP ÚCRLF ©OL« Ú£ 1"USC-ISIF.ARPA L«Âà ÌŶ¡" ¯ÿ "

¡ X

ù´ Ï~ A"XJÑÖìѯK § U¬ £421 اL«e ÑÖÑ ¯K §ë ¬ '4" uà ¯ÿ

§uxHELO ·-"

S: HELO USC-ISIF.ARPA R: 250 BBN-UNIX.ARPA HELO ·-

¡ ëê ²uà ÌŶ¡"

Âà ¤õ A´250 §

¡´gC ÌŶ¡"

X3u& MAIL ·-^5 ²reverse path "~X: S: MAIL FROM:<Smith@USC-ISIF.ARPA> R: 250 OK MAIL ·- ª¥“FROM:” ¡ ´reverse path "XJuà´=ue §@o¦¬ 3reverse path ¥ ¹gC ÌŶ¡ \ reverse path cà" XJ¤õ§Âà A250 " } {§ U £Xe A: 552 451 452

e ; mØ " /?nÑ " XÚ ; mØ

500 Ñ {§ U £Xe A: 501 421 Âà¤õ 1ù^· reverse path À«¥"

{ اÃ{£O ·-" ëê¥ { Ø" ÑÖì ~§ë ò '4"

§ ¤k À«§r“FROM:” ëê¥ forward path \\

· §XJe ux }§Ò¬ ) ØÏ e §ux u <§ ´§ ù ÿXJ2 ½reverse path {§@où ØÏ e XJux } {§Ò¬ ) ØÏ e ØÏ e §ù Ì e Ø´ Я§¤±§MAIL ·-¥ reverse path ±´ §L«XJe ux }§ Ø ux£ e ux< "~X: annCharles@tom.com

1162 , 208

Python ÆS)P


§3.12 SMTP Æ0 MAIL FROM:<> 3uxÂ†Ă˜Ă? e‡ žÿ§Ă‘´Ă˜Â?½reverse path §Ú Ă’;Â? eÂ‡ĂŒÂ‚" u‰X & RECP ¡-^5Â?²forward path "~X: S: R: S: R: S: R:

RCPT TO:<Jones@BBN-UNIX.ARPA> 250 OK RCPT TO:<Green@BBN-UNIX.ARPA> 550 No such user here RCPT TO:<Brown@BBN-UNIX.ARPA> 250 OK

z˜g RCPT ¡-¤þƒ §Ă’ÂŹ3forward path ÂĽO\˜‡Vš"z˜‡forward path XJÂ?½ =uĂŒĂ…§@o˜½Â‡áX=uĂŒĂ… ^S§Â?g=u"˜„5`§Ă‚à ´forword path ÂĽ 1˜‡=uĂŒĂ…§½Ü´ ª8 /" XJ´=uĂŒĂ…§@oÂŚĂ’eg=uÚ¾e‡ žÿ§Ă’ÂŹrÂŚgC Âśilreverse path 1Â˜Â‡ĂŒĂ…œ¥¼£r§ \ forward path ÂĽ" & SN´Â&#x;o DATA ¡-^uuxe‡ SN"~XÂľ S: R: S: S: S: R:

DATA 354 Start mail input; end with <CRLF>.<CRLF> Blah blah blah... ...etc. etc. etc. . 250 OK

Ă‚Ă ÂŹ@Â? ÂĄ ¤k 1Ă‘´e‡ SN"uxêâ žÿÚPOP3 Æaq§^˜ ‡Â?šk“.â€? 1Lêâ(ĂĽ"XJê⼚kÂąâ€œ.â€? mĂž 1§Ă’3mĂž \˜‡“.â€?§ ,ÂŚĂ˜==Â?šÂ˜Â‡â€œ.â€? §Ă‚Ă 3 ɼ3 K \ “.â€? §¢y êâ Ă&#x;²DĂ‘" Ă‚ êâV\3êâ…ÀS" Ă‚Ă Ă‚êâ .

§AT?nn‡…À¼ &E§?n .

§Â˜Â˜¤k…À"

XJ¤þ?n …ÀS &E§Ă‚Ă ATÂŁA250 OK " Âà „3e‡ êâmĂžO\˜1§ ‰eZ§time stamp "Ăš §zÂ˜Â‡ĂŒĂ…Ă‘ ÂŹ3ޥ‹˜‡eZ§@o ‡<Ă‚ & žÿ§ŒĂ’ÂŒÂą e‡´Nolu‡<@p ˆ " annCharles@tom.com

1163Â?, 208Â?

Python ÆS)P


n Python ~^ ÂŹ XJĂ‚à ´ Â˜Â‡ĂŒĂ…§Â?Ă’´8 ĂŒĂ…§@oTĂŒĂ…Â„ÂŹ3e‡êâ mĂžO\˜ 1§ ‰return path §Ú˜1 3 MAIL ¡-ÂĽ reverse path &E" ÚÒ¿›X§ ªĂ‚‡<w e‡ žÿ§Œ e‡ mĂž 1˜1´return path § ¥‹XNĂľeZ(time stamp)&E"e¥´Â˜Â‡#Ă‚ e‡SN ˜‡~fÂľ Return-Path: <@GHI.ARPA,@DEF.ARPA,@ABC.ARPA:JOE@ABC.ARPA> Received: from GHI.ARPA by JKL.ARPA ; 27 Oct 81 15:27:39 PST Received: from DEF.ARPA by GHI.ARPA ; 27 Oct 81 15:15:13 PST Received: from ABC.ARPA by DEF.ARPA ; 27 Oct 81 15:01:59 PST Date: 27 Oct 81 15:01:01 PST From: JOE@ABC.ARPA Subject: Improved Mailing System Installed To: SAM@JKL.ARPA This is to inform you that ... Ă™ ÂĽ 1 ˜ 1“Return-Pathâ€? ´  Â˜ ‡ e ‡ Ă‘ Ă– ĂŹ O \ § 3 MAIL ¡ - ÂĽ ĂŤ ĂŞ " ÂĄ n 1 ´ § z ˜ ‡ Ă‘ Ă– ĂŹ X e Z " Ăš w ÂŒ Âą §JOE k u x e ‡lABC.ARPA DEF.ARPA §DEF.ARPA GHI.ARPA §GHI.ARPA JKL.ARPA §JKL.ARPA ´Ă‚‡<SAM ĂŒĂ…ϴ" Date

ÂĄ To (ü§´e‡ Ăž§

ÂĄ Ă‘´e‡ Š "

XJĂ‚Ă 3Ă‚ ê⃠uyĂœŠe‡ Ă‚ĂśĂ˜U¤þ Ă‚e‡§@oÂŚÂ?ÂŹÂŁ A250 OK §Â?Ă˜LÂŹ )˜‡eÂ‡Â†Ă˜Ă? e‡§ux‰u‡<" 2„ ÂŚ^QUIT ¡-(ĂĽe‡uxL§"~X: S: QUIT R: 221 BBN-UNIX.ARPA Service closing transmission channel

§3.12.3 Ă™Œ¡RSET XJ3uxe‡ L§¼§uĂ uxRSET ¡-§@oLÂŤÂ˜ĂŻuxe‡§Â˜Â˜¤kÂ… À" VRFY ڇ¡-^uu ´Ă„ÂŒÂąuxe‡‰,‡^r"VRFY

ÂĄ Íê´Â˜Â‡^rÂś

ÂĄ" annCharles@tom.com

1164Â?, 208Â?

Python ÆS)P


§3.12 SMTP Æ0 S: VRFY Smith R: 250 Fred Smith <Smith@USC-ISIF.ARPA> S: VRFY Smith R: 251 User not local; will forward to <Smith@USC-ISIQ.ARPA> S: VRFY Jones R: 550 String does not match anything. S: VRFY Jones R: 551 User not local; please try <Jones@USC-ISIQ.ARPA> S: VRFY Gourzenkyinplatz R: 553 User ambiguous. 1˜‡~f¼§£x250 Â?A§LÂŤeÂ‡ÂŒÂąÂ† ux‰Smith "Â?AÂĽÂ?škSmith ^rϴ" 1 ‡~f¼§£x251 Â?A§LÂŤeÂ‡Ă˜ÂŒÂąÂ† ux‰Smith § ´Ă‚Ă ÂŒÂąĂ?L Ă™§ĂŒĂ…=u‰Smith " 1n‡~f¼§£x550 Â?A§LÂŤeÂ‡Ă˜ÂŒÂąÂ† ux‰Smith §Ă‚Ă Â?Ă˜ÂŒÂąĂ?L Ă™§ĂŒĂ…=u‰Smith § ´Ă‚Ă wŠuĂ ÂŒ¹à Â˜Ă Ă™ÂŚĂŒĂ…, USC-ISIQ.ARPA " 1o‡~f¼§£x553 Â?A§LÂŤĂ˜Â?˜‡^r Gourzenkyinplatz " ڇ¡-Ă˜ÂŹĂŠn‡…ÀE¤KÂ?" EXPN EXPN ¡-^r*Ă?˜‡e‡ Lϴ"EXPN Íê´Â˜Â‡e‡aLœ¥§Ă‚Ă X J ڇe‡ L ¤k^r§@oĂ’ÂŹrڇe‡ LÂĽ ¤k^rÂˆÂŁÂ‡uĂ "~ X: S: R: R: R: R: R: R:

EXPN Example-People 250-Jon Postel <Postel@USC-ISIF.ARPA> 250-Fred Fonebone <Fonebone@USC-ISIQ.ARPA> 250-Sam Q. Smith <SQSmith@USC-ISIQ.ARPA> 250-Quincy Smith <@USC-ISIF.ARPA:Q-Smith@ISI-VAXA.ARPA> 250-<joe@foo-unix.ARPA> 250 <xyz@bar-unix.ARPA> z˜1Ă‘Â?šÂ˜Â‡^r ϴ"5Âż Ăľ1Â?AÂĽ250

¥‘k~Ă’§L„kÂ?

A" annCharles@tom.com

1165Â?, 208Â?

Python ÆS)P


n Python ~^ ¬ ù ·-جén À«E¤K " SEND SOML SAML SEND ·-ÚMAIL ·-aq§ØÓ ´§XJ^r ¹ Ìŧ@oSEND · -´re ux ^r ªàþ§ Ø´^r e ¥" 5 >fe ^rÑ´ ¹ ARPA net þ ÌÅâU w>fe "XJ ^r ¹ §Ò ± uxe ^r ¹ªàþ " ´y3 õ ^r´¦^POP3 ÆlÌÅþe1e / Ö§ Ø´ ¹e ÑÖìþ " XJ^rvk ¹§@oÂà¬ux } A" SOML ·- ¿g´SEND or MAIL §L«uxe ^r ªàþ§½öux ^ r e ¥" SAML ·- ¿g´SEND or MAIL §L«uxe ^r ªàþ§¿ ux ^ r e ¥" HELP Âà ù ·- § uàux Ï&E"ù ·- ± kÙ¦·- ëê§^ u , A½·- Ï&E" ù ·-جén À«E¤K " NOOP ö "Âào´ £250 OK " TURN ^u uxàÚ ÂৠҴù ·-

§uxàC ÂৠÂàC ux

à" XJïáÏ é¤ m½ö7a§@oF"3 gë ¥Ó ¤uxÚ Â§ù · -Òék^" 3IP ¥ TCP ë Ø´é[B §¤± Ø^ù ·-"

§3.12.4 ESMTP §3.12.5 ¹@y

annCharles@tom.com

1166 , 208

Python ÆS)P


1oĂ™

Tkinter ? § §4.1 Tkinter0 §4.1.1 Â&#x;o´Tkinter Tkinter ´Â˜Â‡python §´Â˜Â‡N^Tcl/Tk Â?"Tcl/Tk ´Â?ĂŞĂ˜Ăľ (Â? N´Â?˜ )ª² ĂŁ/.ÂĄ Â?" 3ÂŒþêUnix ² ÞÑkTcl/Tk"y3Windows ĂšMacOS ĂžÂ?ÂŒ¹Œ^Tcl/Tk Tk . C Š Ăł Â? 3 Ă„ ĂŤ ÂĽ tkinter ÂĽ §Tkinter.py ´ | ^ tkinter ˜ ‡Python Â?C§^uÂ?Python ^rJø Â?" XĂš

gXã4-1e§¹X windows �~¾ Your App Here(Python) Tkinter(Python Module) tkinter(C) Tk Widgets(C and Tcl) Tk(C) Xlib (C)

ĂŁ 4-1: Tkinter XĂš

gĂŁ

Your App Here (Python) Python A^§S§N^Tkinter.py gv Tkinter (Python Module) Tkinter.py ^urPython ÂĽ LˆÂ?ÂŞ=C¤Â?Tk ¡ĂšĂŤĂŞ" tkinter (C) ^urTkinter.py )¤ Tk ¡-ĂšꐤD4‰Tk )ºÏ§4Ă™)º‰ 1" annCharles@tom.com

1167Â?, 208Â?

Python ÆS)P


o Tkinter ?§ Tk Widgets (C and Tcl) Tk ´dC ĂšÂ˜ĂœŠ Tcl ¤ " Tk (C) Tk .

C ÂŠĂłĂœŠ"

Xlib (C) N^X ¼§ĂšX Server Ă?&" Python ^rĂ˜ÂŹÂ† N^ tkinter § ´Ă?LTkinter.py m ÂŚ^ÂŚ" Tkinter Ă˜´Â?˜ Python ĂŁ/?§ Â?§´Ă™ÂĽ' 61 ˜‡" ÂŒ A:´ª ² "²w ":´5UĂ˜ Ă?§Ă?Â?Tcl/Tk Â?´)Âş5Šó§Python Â?´§^Python )¤Tcl/Tk “è§, 2^Tcl/Tk )º‰1§Â„Ă? ,'† N^. ĂŁ/ Â? ‡ú§ ĂšÂ?´ŒÂ?ª² ¤GĂ‘ “d" ´ÂŒþêÂœše§\Ă˜ïå¤ZĂž ‡UĂœ§IÂ? jº¤¹Â˜Â„´ÂŒ¹áv‡Œ " Â˜Â„ÂŚ^Tkinter Â?{´ from Tkinter import * Â?ÂŒ¹´ import Tkinter ´Tkinter z‡ŸêĂša c¥Ñ‡kTkinter.somefunc() § ĂĽ5ʤžm" Â&#x;o´Widget ? Widget ´Button(UĂœ) §Canvas(xĂ™) §Menu(èß) §Label(Ăź 1 I \) §Message(Ăľ 1 I \) §Listbox( L) §Entry (Ăź 1 Ă‘ \ Âľ) §Frame(Âľ e) §Radiobutton(þĂ€Â˜ ßÀ¾) §CheckButton(EÀ¾) §Scrollbar( EĂ„^) §Text(Ăľ 1Š Ă‘\Âľ) §Scale(3˜½Â‰ÂŒSĂ€JÂ˜Â‡ĂŞÂŠ EĂ„^) TopLevel(IÂ?) Ú¥" Â&#x; o ´option ? ¤ k Widget Ă‘ k ĂŠ Ăľoptions § Â? )fg(c Âľ Ăš) §bg( Âľ Ăš) §font(iN) §command(¯‡?nŸê) §text(SN) "

§4.2

Hello Tkinter §S

§4.2.1 {Ăź ~f ÆSŠóÑ´l“Hello Worldâ€? mŠ§¡Â?Ă˜Âť~" # File: hello1.py # \ Tkinter from Tkinter import * # MĂŻÂ˜Â‡ root Widget # Ă?~z˜‡ Tkinter §SĂ‘k˜‡§ Â…Â?k˜‡ # root widget annCharles@tom.com

1168Â?, 208Â?

Python ÆS)P


§4.2 Hello Tkinter §S # Ϋ˜‡{Ăź IÂ?§Â‘kIK9§Ăš>¾Úٌ Windows # Manage Jø CÂť" # 7L3Mïٌ Widgetƒc§MĂŻ root widget" # Â?ÂŒÂąĂ˜Mï§Tkinter ÂŹgĂ„Â?\MĂŻÂ˜Â‡" root = Tk() # MĂŻÂ˜Â‡ Label§ w§ # root ´ w master(IIÂ?)§ # w ´ root slave (fIÂ?) # Ăšp âŠk:Ă˜Ă“u Windows§ Windows e # ´ parent window§ Ăš child window" # text ´ w ˜‡ option (À‘)§LÂŤ w ÂĽ # ‡wÂŤ SN§ÂŒ¹´Ši½Üã¥" w = Label(root, text="Hello, world!") # w MĂŻÂƒ §¿vkĂ˝ wÂŤ3Âś4¼§ # Â?k3 pack ƒ §âUŠâ Label ÂĽ SN§OÂŽĂ? # Label ÂŒ §Â˜  Â˜§, wÂŤ3Âś4Ăž" w.pack() # ?\ÂŻÂ‡ĂŒÂ‚§ Ă‚5g^r ¯‡§Â‰1ĂŠA # ¯‡?n§Â† ^rN^ quit() ½Ü IÂ? '4 " # mainloop() „‡?nSĂœ widget Â?#§5g # Ăš Windows Manager Ă?&" root.mainloop() $1§S %python hello1.py $1(JXĂŁ4-2

ĂŁ 4-2: hello1.py $1(J ^B0 ˜eWM(Windows Manager)§Ă™GX Windows ^rÂ?NĂŠWMĂ˜ÂŹ))" ´Windows ^rĂ’ÂŹĂŠ)) "3X NX( ¼§IÂ? >¾§IK9§'4UĂœ§  ÂŒz§ z§IÂ? ÂŁĂ„§Â˜ÂŒ § Ă‘´WM 5‰ §WM Ă˜L´Â˜Â‡ĂŠĂ? annCharles@tom.com

1169Â?, 208Â?

Python ÆS)P


o Tkinter ?§ X Client§Ă?LIO ÆÚX Server Ă?&"?Ă›Â˜Â‡X client §SĂ‘ÂŒÂąĂšWM 5Ă?&" 3Windows XĂš¼§WM Ăš ‡ÜŠXĂš Ăœ3˜ü§ÊJŠ Â˜Ă™§ ´¡lWin XP ĂšWin 2000 w §k˜ Windows §SÂŒÂąĂ?L,Å› ¤WM ĂľU§4Windows *wĂĽ5”MacOS §½ÜX e ٌWM J"

§4.2.2 ,˜‡{ߧS 3˜‡' ÂŒ §S¼§ Ă?r˜‡\ §S 3˜‡a¼§Xe # File: hello2.py from Tkinter import * class App: def __init__(self, master): # MĂŻÂ˜Â‡ Frame ^uÂ?šĂ™ÂŚ widget frame = Frame(master) frame.pack() #MĂŻÂ˜Â‡UĂœ self.button = Button ( frame, # master widget text="QUIT", fg="red", command=frame.quit ) self.button.pack(side=LEFT) self.hi_there = Button(frame, text="Hello", command=self.say_hi ) self.hi_there.pack(side=LEFT) def say_hi(self): print "hi there, everyone!" root = Tk() app = App(root) root.mainloop()

$1(JXã§4.2.2 XJ\Uâ€?Helloâ€? UĂœ§3›› ދ<“hi there, everyone!â€?" XJw ´Â˜Â‡widget§w.pack(side=LEFT) LÂŤ{˜w Â?ÂŞ" annCharles@tom.com

1170Â?, 208Â?

Python ÆS)P


§4.3 Widget ˜

ĂŁ 4-3: hello2.py $1(J

§4.3 Widget ˜ Tk ÂĽ z˜‡widget Ă‘kĂŠĂľoption §Ă?LUCĂš option ÂŒÂąUCwidget *" ;. option k››wÂŤ SN§ôĂš§ÂŒ §¯Â‡?nŸê §Tkinter Jø ĂšÂ˜ .ÂĄ^u?n¤k option. Ă?~kÂąeÂ?{?nwidget option: • ÂŒ¹Œ^eÂĄ Â?{3MĂŻwidget žÿ ˜widget options" widgetclass (master , option=<value> ...) ~X: w = label(root,text="hello",fg="red") MĂŻÂ˜Â‡widget § ‰w §Œ master widget ´root §Œ option ÂŚ^ ÂĄ ĂŤĂŞ 5‰½ "¤k widget option Ă‘k%@Š§¤¹ {Ăź MĂŻÂ˜Â‡widget Â?{ ´¤k option Ă‘ÂŚ^%@Š§Â?Ă’´Ă˜Â?½?Ă›option§Â?IÂ?½widget master widget§XJ\ĂŠB {§$–Ímaster widget Â?ÂŒÂąĂ˜^Â?½§Tkinter ÂŹ^ C ÂŚ^L master widget ŠÂ?%@ master widget " • w.cget(option) ˜‡widget option Š"w ´Â˜Â‡widget "¤k widget class Ă‘kr__getitem__ N w.cget Þ§¤¹ŒÂ‚߇vkÂ&#x;oÂŤO"¤¹ ^w[option] ˜ ÂŒÂą ˜‡option "~X: w = Label(text="abc") print w.cget("text") print w["text"] # vkÂŤO§Ă‘ÂŒÂą abc ¡ú w[’text’] Â?ÂŞÂ?Ă?w˜ " • ^w.configure ½Üw.config ˜option Š"w.config ´w.configure  §¤ ¹þUĂžvkÂŤO"^{ĂšMĂŻwidget ÂžĂżÂ˜ " w.config(option=<value>, ... ) ~X: annCharles@tom.com

1171Â?, 208Â?

Python ÆS)P


o Tkinter ?§ w.config(text="xxx") ¤k widget class r__setitem__ N w.config Þ§¤¹ w["text"] = ’xxx’ J˜ " XJkĂŠĂľ option ‡ ˜§@o^config Â?Ă?w˜ "XJÂ?k˜‡options ‡ ˜§@o^ ÂĄ Â?ÂŞÂ?Ă?w1 " • config ¤ ŸêXJĂ˜Â‘?Ă›ꐤ@oÂŹ ˜‡widget ¤kÂŒÂą ˜ option ϴ"w.keys() Â?˜ "¡Â?U Œ^w.keys() §Œ ¿ÂÂ?Â˜Ă™§{Ăź"~X: for k in w.keys(): print "%s = %s"%(k,w[k]) ÂŒÂąÂ‹<˜‡widget ¤k option " nÞ¤ã§Â–ÂŻÂ˜Â‡widget option kĂź@Â?{" w.config() w.config(optionname=optionvalue,...) w.cget(’optionname’)

w.keys() w[’optionname’]=optionvalue w[’optionname’]

äNÂŚ^@ÂŤd‡<S.ݽ§¡ú 1 ÂŤÂ?ÂŞÂ?Ă?"

§4.4 Geometry Manager(AĂ›+nĂŹ) Â&#x;o´Geometry Manager? ? LGUI <kĂš ²{§{˜Ă?z˜‡Widget ´Â˜Â‡ĂŠÂ„ÂĄ ÂŻÂœ§Ú‡N z˜‡Widget g ÂŒ §4ÂŚU ʤ Â?šĂšwÂŤÂŚSĂœ SN§Â„‡˜Ă?Úٌ 73Widget ƒm ĂĽl§4Œ‚Â?ƒm ĂĽlŒÞÞ!§Â„‡ ˜Ă?ÂŚ3Master ÂĽÂ Â˜§XJMaster ÂŒ UC §ATXĂ›N Widget ¤k" „¥ ÂŻÂœĂ’ ‰OÂŽĂ… ‰§Tk Jø A‡Geemetry Manager"ÂŒÂąÂ?Ă?\ ¤Ú

ĂľU§Â?^ĂŠ “è§Ă’ÂŒÂą4\ .ÂĄwĂĽ5ĂŠ;Â’" ÚÚDelphi ½ÜVB ÂŒĂ€z?§Â‚¸§kĂŠÂŒĂ˜Ă“"VB ´Â˜ÂŤWYSIWYG§What you see is what you get (¤ „ = ¤ ) Â? ÂŞ §Geometry Manager ´ ˜ ÂŤWYTIWYG §What you think is what you get (¤ÂŽ=¤ )"k:”TeX(LaTeX) ĂšWord ÂŤO" 3VB ¼§\rWidget {˜3=§\w §$1 (JĂ’Ăš\w ˜ § ´\ Â‡Ă˜ä Ă€Jâ€œÂ‚ÂŞ/ĂŠĂ â€? èߧrŒ‚Êà §Â˜3Ăœ¡  Â˜§ ĂšI‡²â[ "{ *gĂš<Nó§Ă† *g§âU4Œ‚wĂĽ5ĂŠ{" 1

Â?N\ "{*:Ăš¡Ă˜Â˜ "

annCharles@tom.com

1172Â?, 208Â?

Python ÆS)P


§4.4 Geometry Manager(AĂ›+nĂŹ) ^Geometry Manager §\I‡^˜ ĂŤĂŞwŠŒ\Ž‡ JĂ’ÂŒÂą §Â˜½´\ÂŽ ‡ " ˜„Tk knÂŤGeometry Manager : • Pack • Grid • Place e¥ŠO0 "

§4.4.1 Pack +nĂŹ kA‡âŠy0 ˜e" cavity : master widget Ăž ˜ m § L ÂŤ Š ˜ Ăœ Š ˜ m ‰ ˜ Ăœ Šslave widget ƒ §master widget ބÂ?e ˜m§^uŠ ‰ÙŒ„vk{˜Ă? slave widget " parcel : lcavity ¼Š Ă‘ ˜‡˜m§^u{˜˜‡slave widget " zg‰˜‡slave widget Š ˜m žÿ§Ă‘´lcavity ÂĽ ˜‡parcel§, 2 rslave widget {˜3parcelÂĽ", lcavity ÂĽ~ parcel ÂŒ § ˜‡# cavity § UYŠ §Â† ¤k slave widget Ă‘{˜ ." Pack + n ĂŹ ÂŚ ^ Â? { ĂŠ { Ăźw.pack(options) "w ´ ˜ ‡slave widget" ~ ^ options k: Pack+nĂŹ~^ option side LÂŤrw ˜3@‡>Ăž"ÂŒ¹´TOP (Ăž) §BOTTOM( e)§LEFT( †)§RIGHT( m)" padx Ăšpady LÂŤparcel z˜‡>Ăšw ƒmĂ˝3 ˜m" ipadx Ăš ipady LÂŤw z˜‡>Ăšw SÂ?š SNƒm Ă˝3˜m"w ÂŹĂ?dCÂŒ" fill ÂŒ¹´None, x, y , both"XJparcel ÂŒ §@oҏŠâfill Š§O\slave widget ÂŒ " • • • •

None: L‘¹slave widget 5 ÂŒ " X : LÂŤÂ?*ÂŒslave widget °Ă?" Y : LÂŤÂ?*ÂŒslave widget pĂ?" BOTH: LÓž*ÂŒslave widget °Ă?ĂšpĂ?"

Š 5Âż §fill ´Â?slave widget ÂŒ Ăšparcel ÂŒ ƒm'X§Ý½slave widget N UCgC ÂŒ §5¡Aparcel ÂŒ " annCharles@tom.com

1173Â?, 208Â?

Python ÆS)P


o Tkinter ?§ anchor LÂŤ3parcel ÂĽÂ˜Â˜slave widget Â?ÂŞ"ÂŒ¹´¹e Š""ŽŠ´CENTER" W N NW SW CENTER

‚†˜˜ Â‚ĂžÂ˜Â˜ Â‚Â†ĂžÂ˜Â˜ ‚†e˜˜ ˜3 ÂĽm

E S NE SE

‚m˜˜ ‚e˜˜ ‚mĂžÂ˜Â˜ ‚me˜˜

ĂšpŠ 5Âż ´§XJfill Š´X §@oanchor ´W ĂšE Ă’Ăƒ¤¢ §Ă?Â?slave widget °Ă?Ž²´ ÂŒ§Â‚†˜„´Â‚mÂ˜Ă’vkÂ&#x;o¿Â "Ă“ n§XJfill Š´Y §@oanchor ´N ĂšS Ă’Ăƒ¤¢ "XJfill Š´BOTH §@oanchor option Ă’vk¿Â "ÚÊĂ˜Ă?§grid +nĂŹ3ĂšÂ˜:ĂžkU?" expand ÂŒ¹´0 ½Ü1"XJ´1 §LÂŤslave widget Šâe¥¤` Â?{§rmaster Â?{˜mŠ ‡z˜‡slave widget parcel"XJ´0 §4Â?{˜m˜X" Š 5Âż ´§expand ´Â?master Â?{˜mĂš¤kslave widget parcel ƒm 'X XJr¤k slave widget Ă‘{˜Ă? § ´Â„kÂ?{˜m§ŒÝ½´Ă˜´rmaster Â?{˜m‰¤kparcel " 5¿§¹Þ¤k option Xside§padx , pady , ipadx , ipady , expand, fill Ă‘´N ^pack() žÂ?½ option§ Ă˜´MĂŻwidget žÿÂ?½ option" Pack ÂŽ{ z˜‡master widget Ă‘k˜‡packing list ^u+nÂŚSĂœ ¤kslave widget"MĂŻÂ˜ ‡# slave widget§3master widget Packing list (—J\˜‡slave widget"„Œ Âą^in , after , before Ăšn‡option UC^S" Pack +nĂŹUĂŹpacking list o widget ^S§Â˜Â˜{˜z˜‡widget"3fm Š§master widget SĂœ¤k ˜mĂ‘´Â˜ §Ă’´cavity (Â˜Ă‰)" Pack UĂŹÂ˜eĂš½¿Ă‚{˜z˜‡slave widget" 1. áX˜‡cavity ˜‡>ƒe˜‡Ă?/§ ‰parcel (Â?K)§äNá=˜‡>´dside option Â?½ " XJside = TOP ½Üside = BOTTOM §@oparcel °Ă?Ă’´cavity °Ă?§pĂ? Ă’´slave widget ‡Œ pĂ?§2\Ăžpady Ăšipady Ú߇options ¤Â?½ êŠ" XJside = LEFT ½Üside = RIGHT §@oparcel pĂ?Ă’´cavity pĂ?§°Ă? Ă’´slave widget ‡Œ °Ă?§2\Ăžpadx Ăšipadx Ú߇options ¤Â?½ êŠ" Âą parcel „ŒUĂ?Â?expand option ¤Â?½ Š CÂŒ"XJ¤k slave widget Ă‘ ˜Ă? §uymaster widget „kĂľ{ ˜mvkÂŚ^§@oҏŠâexpand option annCharles@tom.com

1174Â?, 208Â?

Python ÆS)P


§4.4 Geometry Manager(AĂ›+nĂŹ) 5UC¤kparcel ÂŒ "XJexpand option ´0 §@oĂ’ÂŽ §Ă’4@ ˜ /Â?˜XĂ? "XJexpand option ´1 §@oĂ’rÂ?e ˜mĂž! Š ‰¤k parcel"XJÂ˜Â‡ÂŒÂą*ÂŒ slave widget side option ´left ½Üright §@orĂľ { Y²ül²ÞŠ Œ‚"XJÂ˜Â‡ÂŒÂą*ÂŒ slave widget side option ´top ½Übottom §@orĂľ{ R†ül²ÞŠ Œ‚"Ăš Â?ĂŠ"y(š5§grid + nĂŹO\ ­ Vg§´k¤U? " 2. pack +nĂŹslave widget Ă€JĂœ¡ pĂ?Ăš°Ă?"°Ă?˜„´widget ¤I°Ă?\Þß ipadx §pĂ?´Â˜Â„´widget ¤IpĂ?\Þß ipady §Â?Â&#x;o´ß ? ´Ă?Â? †mĂ‘I‡3Ă‘ipadx ĂĽl§Ă“ ĂžeÂ?Ă‘I‡þ3Ă‘5ipady ĂĽl" ´XJfill option ŠXJ´X ½ÜBOTH§@o*ÂŒ°Ă?§slave widget °Ă?´parcel ° Ă?~ Ăź padx Š§Ă“ XJfill option Š´Y ½ÜBOTH §@oslave widget °Ă?´parcel °Ă?~ Ăź pady Š§ 3. pack +nĂŹrslave widget ˜3parcel ÂĽ"XJslave widget 'parcel §@oҊ âanchor option 5˜˜slave widget§parcel Â?e ˜mÂ?Ă˜ÂŹÂ‰Ă™ÂŚslave widget ÂŚ ^ "XJpadx option ½Üpady option ÂŠĂ˜´0 §@o3parcel >.Ăšslave widget >.ƒmo´Â‡3Ă‘5padx Ăšpady @oĂľ ˜x˜m" ˜˜Ă?˜‡slave widget §pack +nĂŹÂŹ~ parcel §Â?e˜‡' cavity ^ 5˜˜e˜‡slave widget"XJcavity ˜mĂ˜ ˜˜˜‡slave widget §@oڇslave widget ÂŹĂ“âcavity ¤k ˜m" cavity  Â–0 žÿ§Ă™ÂŚ Â?e slave widget Ă’ wĂ˜ §Ă˜Âšmaster widget CÂŒ" ˜„œšemaster widget ÂŹgĂ„CÂŒ§âŠ ‰Geometry Propragation (AĂ›DĂ‚§ ÂŒ DĂ‚)"Geometry propragation ÂżgĂ’´`§gĂ„N master widget °Ă?Ăšp Ă?§^5 Ă? ˜˜¤k slave widget §¿Â…ÂŹ3widget g( ÂĽD4ÂŒ "Â&#x;o ‰widget g( ? ¡Â‚ master widget Ăšslave widget 'X" master widget q ´,˜‡widget slave widget"Ăš Ҕ/¤ ”ŒŒ§IŠ§ f§ÂšfĂš g' X"Â?ÂŒÂą`´ä“§äª§äŠ 'X" Ă„kOÂŽä“widget ÂŒ §ä“widget vkslave widget §ŒÂ‚ÂŹgCOÂŽgC ÂŒ §vÂąNBe¤kslave widget ¤kSN§, Â?šÚ‡äªwidget ÂŒ Ă’ÂŒÂąÂŠâ Œ¤slave widget ÂŒ UC§Ú Â˜Â†Â•ĂžD4§Â† TopLevel" Ăš  ª (JĂ’´¤k Widget {˜ ›ŠĂœn" ,§k žÿÚĂ˜´¡Â‚Ž‡ (J§@o¡Â‚ÂŒÂąĂ?LN^eÂĄ ŸêĂŠÂŽGeometry Propagation" w.pack_propagate(’true’) ÂŚ ^Pack + n ĂŹ ž Ăż § ² ~ ÂŹ ÂŚ ^frame widget § ^ u r ˜ |widget w ¤ ˜ ‡widget" annCharles@tom.com

1175Â?, 208Â?

Python ÆS)P


o Tkinter ?§

§4.4.2 Grid +nĂŹ ÂŚ+Pack ĂŠĂ˜Â†§ ´§Êþ§S @Â?Grid +nĂŹÂ?Ă?^" Â… - <ÂŹÂ? ^Grid § Ă˜^Pack"Â?NŒ´Ê "¡@Â?ˆkˆ `:" ¡@Â?Grid +nĂŹ Vg{ߧþUrÂŒ§(š§(¢'Pack r˜ " ÂŚ^Grid Â?{Â?ĂŠ{ߧĂšPack aq§N^w.grid(options) §w ´Â˜Â‡slave widget" Grid + n ĂŹ r ˜ ‡master widget ¤ k ÂŒ ^ ˜ m Š ¤ ‚ G ĂŠ Ăľ ° " z ˜ ° ‰˜‡Cell §ĂšPack +nĂŹÂĽ parcel VgĂŠÂƒÂ”"^row §column §rowspan §columnspan Ă’ÂŒÂą(½Â˜Â‡cell "ke~^option" ~^ options row Â?²3@˜1 column Â?²3@˜ rowspan Â?²Ă“ A1 columnspan Â?²Ă“ A ipadx ipady ĂšPack +nĂŹ ÂżĂ‚ÂƒĂ“"LÂŤslave widget SĂœO\ W¿ül" padx pady LÂŤslave widget >.Ăšcell >.ƒm W¿ül" sticky ÂŒ¹´N §W §S §E §Â?š ´Pack +nĂŹÂĽ fill §anchor ĂľU"LÂŤ Cell 'slave widget ÂŒ žÿ§XĂ›{˜slave widget§7‡ žÿ§O\slave widget p Ă?½Ü°Ă?" XJ´ß‡ N L§Â•ĂžÂ‚§aqPack +nĂŹÂĽ anchor= N " XJ´ß‡ |ĂœL§XN+S §LÂŤO\pĂ?§aquPack +nĂŹÂĽ fill = Y " XE+W §LÂŤO\°Ă?§aquPack +nĂŹÂĽ fill = X " X J Ăź ‡ | Ăœ ´N+E L ÂŤ Ă˜ O \ p Ă? ½ ° Ă? § • m Ăž Â? { ˜ § ƒ ufill=None§anchor=NE Ă™§aq" XJ´þ‡|ĂœN+W+S+E LÂŤÂ˜3ÂĽm"aquPack +nĂŹÂĽ fill=BOTH " XJĂ˜ ˜sticky Š§LÂŤĂ˜O\pĂ?Â?Ă˜O\°Ă?§Â˜3ÂĽm§aquPack +n ĂŹÂĽ anchor=CENTER§fill=None " annCharles@tom.com

1176Â?, 208Â?

Python ÆS)P


§4.4 Geometry Manager(AĂ›+nĂŹ) Grid +nĂŹ ÂŽ{ kn‡Ú½: 1. OŽ– IÂ‡ĂľÂŒ /Â?§Ă’ÂŒÂą{˜e¤k slave widget " 2. ^ĂžÂ˜ĂšOÂŽ (JĂšmaster widget ¢SÂŒ ' §XJĂ˜Â˜ ÂŒ§@oĂ’O\½ Ăś~ master widget ÂŒ " 3. Šâz˜‡slave widget sticky options §{˜¤k slave widget " 31Â˜Ăš¼§Ă„kOÂŽ¤kÂ?Ă“Â˜1(½ ) cell °Ă?(½pĂ?)§Â?Ă’´rowspan=1 (½colspan=1) cell "z˜1(½ ) °Ă?(½ÜpĂ?)Ă’´Ú˜1(½ )¼¤I‡  ÂŒ° Ă?(½ÜpĂ?)§¹ y˜ e¤kslave widget "z˜1§z˜ ÂŒ Ă‘ §Ú z ˜‡cell ÂŒ Ă’(½ " , 3 Ă„Ă“Ăľ1(½Üþ ) cell §cell ¤Ă“ ĂŤY 1(½ ) ‰˜‡cell group §cell group °Ă?(½ÜpĂ?)´|S¤kcell °Ă?(½ÜpĂ?) Ăš"XJcell group

ÂŒ§v ˜ eÂƒĂŠA slave widget §@o Ă? §Â‘Âą|S ¤k1(½ ) °Ă?(½p Ă?)Ă˜C"XJÂ˜Ă˜e§Ă’I‡O\|SCell z˜1(½ )Ă?(½pĂ?)"O\ Â?{Ă’´ÂŠ â1(½ ) weight( ­) U'~5O\cell group ÂĽz˜1(Ăś ) °Ă?(ĂśpĂ?)§weight ÂŒ O\ þ§weight O\ §weight ´0 Ă’Ă˜O"XJcell group ¼¤k cell weight Ă‘´0§@oĂ’²ÞO\|S¤k cell °Ă?(½pĂ?)" Â?ge §ÂŒÂą(½z˜ (½1) °Ă?(½pĂ?)§Ú z˜‡cell Ăšcell group ÂŒ Ă’(½ " ˜˜1 weight§ÂŒ¹Œ^grid rowconfgure Ÿê§~X m.grid_rowconfigure(0,weigtht=2) r101 weight ˜Â?2 " ˜˜ weight§ÂŒ¹Œ^grid columnconfgure Ÿê§~X m.grid_columnfigure(0,weigtht=2) r10 weight ˜Â?2 "Ù¼m ´¤kslave widget master widget" 31 Ăš¼§XJmaster widget š~ÂŒ§Â„kĂŠĂľ Â?{˜m§@oĂ’ÂŹrR†(½ ĂśY²) Â?{˜mŠ ‰¤k 1(½Ü )§ÂŠâz˜1(½Ü ) weight ŠU'~Š §weight ÂŒ Ăľ §weight §weight Â?0 Ă˜ "XJ¤k1(½Ü ) weight Ă‘´0 §@oĂ’rR†(½ÜY²) Â?{˜m²ÞŠ 3Ăže(½Ü†m)ßà §Â?Ă’´Ă˜ÂĽ ˜˜"Ăš §^weight Vg ¤ Pack +nĂŹÂĽ expand option ĂľU" nÞ¤ã§Grid +nĂŹÂĽ option ‡'Pack +nĂŹÂĽ option ‡ Ăľ" ´þU %'ƒÂ?\(š§Â?\rÂŒ§Pack U‰ §Grid A Ă‘U‰§Grid U‰ §Pack I‡˜ Â˜ĂŠĂľ frame ÚÊþ option âU ¤" annCharles@tom.com

1177Â?, 208Â?

Python ÆS)P


o Tkinter ?§ Place +nĂŹ Place ÂŒ Âą ° ( ˜ ˜ ˜ ‡slave widget  Â˜ Ăš ÂŒ § a q uVB ÂĽ top§left §bottom §right ĂĄ5"Ăš Ê̆§Â˜Â„Ă˜^"XJ\Ă˝ I‡Úo‰§@oĂ’ ĂƒĂžĂ? "– ¡6ÂžĂ˜ÂŹ^ÂŚ"

§4.5 Widget ÂŞ dNĂľ widget Ă‘|¹Ó option §Ú option ½Ă‚ widget Ă„ ª§Â?) Ă´Ăš§iN "

§4.5.1 Ă´Ăš ÂŒ Ăľ ĂŞ widget # N ^ r ˜background option Ăšforeground option 5 U C ˜ ‡widget c¾ÚÚ ¾Ú"cÂľĂšÂ˜Â„´widget Þ¥Ši Ă´Ăš" bg Ăšfg ´background Ăšforeground {ÂĄ"XJ\‹i' ú½Ü' B§@oĂ’ ^bg Ăšfg “Obackground Ăšforeground" 3Â?½ôĂš žÿ§ÂŒÂąÂ† Â?½RGB n‡ŠÞ Š§Â?ÂŒÂąÂ?½ôĂš Âśi§ Xred, green " Ă´Ăš Âśi Tkinter škÂ˜Â‡Ă´Ăš ê⼧^uÂ?š¤kĂ´Ăš ϴÚôÚ¢SRGB Š ĂŠA 'X"êâ¼¼Â?š~^ Ă´Ăš§XÂľred , yellow , blue , green §lightblue §Â?Â?) ˜ Ă˜~^ ´Ê¤ Ă´Ăš§XMoccasin, PeachPuff, etc. 3X windows XĂš¼§ôĂš ÂśidX windows ½Ă‚§ÂŒÂą3ĂŠ rgb.txt §Â˜Â„ 3/usr/X11R6/lib/X11/ 8šeڇŠÂ‡ÂĽÂ?š ¤kôڜiÚôÚ RGB Š ĂŠA 'X" 3Windows XĂše§ÂŒ¹Œ^Windows XÚôÚ(ÂŒÂąĂ?L››¥†UC) SystemActiveBorder, SystemActiveCaption, SystemAppWorkspace, SystemBackground, SystemButtonFace, SystemButtonHighlight, SystemButtonShadow, SystemButtonText, SystemCaptionText, SystemDisabledText, SystemHighlight, SystemHighlightText, SystemInactiveBorder, SystemInactiveCaption, SystemInactiveCaptionText, SystemMenu, SystemMenuText, SystemScrollbar, SystemWindow, SystemWindowFrame, SystemWindowText. 3Macintosh ¼§ÂŒ¹Œ^eÂĄ XÚôÚ: SystemButtonFace, SystemButtonFrame, SystemButtonText, SystemHighlight, SystemHighlightText, SystemMenu, SystemMenuActive, SystemMenuActiveText, SystemMenuDisabled, SystemMenuText, SystemWindowBody. annCharles@tom.com

1178Â?, 208Â?

Python ÆS)P


§4.5 Widget ÂŞ Ă´Ăš œ¥´Ă˜ŠÂŒ " Â…k Ă´Ăš ÂśiÂŒÂą3Ăźcƒm\˜‡˜‚" Xâ€?light blueâ€? â€?LightBlueâ€? ´Â˜Â‡Ă´Ăš" RGB ôڊ Â„ÂŒÂąÂ?½RGB n‡ŠÞ Š§5Â?½ôĂš"‚ª´ #RGB,#RRGGBB, #RRRRGGGGBBBB ~X: w["fg"]="#f00" w["fg"]="#ff0000" w["fg"]="#ffff00000000" Ă‘´rc¾ÚU¤ÚĂš"RGB n‡ŠÞĂ‘AT´Â›8?›"eÂĄ{Ăź ~f§`²

XĂ› ˜RGB ŠÞ" tk_rgb = "#%02x%02x%02x" % (172, 182, 220) tk_rgb = "#%04x%04x%04x" % (172, 182, 220) w.wininfo_rgb() ÂŒÂąrĂ´ĂšϴÂ€ĂˆÂĄÂ?Ă´Ăš RGB ŠÞ"X rgb = widget.winfo_rgb("red") red, green, blue = rgb[0]/256, rgb[1]/256, rgb[2]/256 5Âżwinfo_rgb ÂˆÂŁ ´Â‰ÂŒ´0 – 65535 §XJ‡ 0 – 256 ‰ŒS Š§Â‡Ă˜ Âą256 âÂŒ¹§Â?Ă’´mÂŁ8  "

§4.5.2 iN Tkinter ÂĽ widget #N^rÂ?½iN"Â˜Â„Ă˜I‡Â?½iN§Ă?Â?Tk ÂĽÂŒþê { Ăź widget §XLabel §Button §Ă‘kĂŠĂ? %@iN" 3Â?½iN žÿ§^font option §Tkinter ÂŒ¹Œ^Ă˜Ă“Â?ÂŞÂŁĂŁiN" • • • •

iNÂŁĂŁĂŽ(font descriptor ) ^rg½Ă‚iNœ¥§Œ^tkFont ÂŹ" XĂšiNϴ X iNÂŁĂŁĂŽ( X font descriptor)

iNÂŁĂŁĂŽ(font descriptor) lTk 8.0 mŠ§Tkinter ÂŒ¹Œ^Ă•ĂĄuäNXĂš iN£ã§kĂ?uª² ?§"ÂŒ ÂąĂ?LÂ?½iNx§iNpĂ?§ĂšĂ™ÂŚÂ˜ ÂŒĂ€ iNº‚(font style)5Â?½iN"X annCharles@tom.com

1179Â?, 208Â?

Python ÆS)P


o Tkinter ?§ ("Times", 10, "bold") ("Helvetica", 10, "bold italic") ("Symbol", 8) iNº‚(font style) ´Â?iN´Ă˜´\o§´Ă˜´ N" XJ==‰Ñ iNx œ¥§@oĂ’ÂŹ %@ iNpĂ?§ĂšiNº‚" XJiNx œ¥¼Ă˜šk˜‚§Â?ÂŒÂą==‰Ñ5˜‡iĂŽG^5ÂŁĂŁiN"Â„ÂŒÂą O\iNpĂ?ĂšiNº‚ ½Ă‚" "Times 10 bold" "Helvetica 10 bold italic" "Symbol 8" 3Windows ÂĽ~^ iNÂ?): Arial (corresponds to Helvetica), Courier New (Courier), Comic Sans MS, Fixedsys, MS Sans Serif, MS Serif, Symbol, System, Times New Roman (Times), and Verdana: XJiNxœ¢¼šk˜‚§@oĂ’7L^1Â˜ÂŤLˆÂ?ÂŞ5LÂŤiN" ~^ iNº‚k: normal, bold, roman, italic, underline, Ăšoverstrike. 3Ă˜Ă“ ² Þ§Tk 8.0§gĂ„rĂš ~^ iN§X§Courier, Helvetica, ĂšTimes N ² iNLˆÂ?ªÞ§ Â…§XJiNN ”} {§Â?ÂŹĂŠÂ˜Â‡ bC i N5“O"¤¹3Â?½iN žÿTk 8.0 l5Ă‘Ă˜ÂŹ wÂ†Ă˜ "XJĂŠĂ˜  bC i N§@oĂ’´^%@iN" ´Tk @Â? bC iN§k žÿ¿Ă˜´\Ž‡ §¤¹Ă˜ ‡LĂľ Â?‚Ú‡A5" Windows e Tk 4.2 Â?|¹ÚiN LˆÂ?ÂŞ" ÂŚ^tkFont Font a5Â?½iN Ă˜ ^ i N ÂŁ ĂŁ ĂŽ(font descriptor) ÂŁ ĂŁ i N ƒ § „ ÂŒ Âą Ă? LtkFont 5 Â? ½ i N"Font ÂŹÂĽ tkFont a§ÂŒÂą^5Â?½iN"?Ă›Tkinter I‡iN ꐤ\Ă‘ ÂŒÂą^tkFont 5Â?½"~X: annCharles@tom.com

1180Â?, 208Â?

Python ÆS)P


§4.5 Widget ÂŞ tkFont.Font(family="Times", size=10, weight=tkFont.BOLD) tkFont.Font(family="Helvetica", size=10, weight=tkFont.BOLD, slant=tkFont.ITALIC) tkFont.Font(family="Symbol", size=8) myfont=tkFont.Font(...) ˆ ÂŁ ˜ ‡ ĂŠ – ‰myfont § @ o Ă’ ÂŒ Âą ^w.config(font=myfont) 5 Â? ½widget w i N ´myfont ¤ ÂŁ ĂŁ i N " Ăš k ˜ ‡ Ă? ? ´ § X J ÂŚ ^myfont.config(size=40) § @ o ¤ k ÂŚ ^myfont Š Â? i N widget iNĂ‘gĂ„Â?# §âŠ ‰font propagate "ʤ"Ăš 3§S¼§ÂŒÂąÂ‰Â˜ |aq widget Â?½iNmyfont §, Â?‡?U myfont @oĂšÂ˜|widget iNĂ‘ÂŹ Â?#" tkFont.Font |Âąoption XL4.5-1: Option

a.

ÂŁĂŁ

family size weight slant underline overstrike

string integer constant constant flag flag

iNxϴ iNÂŒ §ß point §XJ´Kê§ß ´pixel NORMAL „´BOLD §%@´NORMAL. NORMAL „´ITALIC §%@´NORMAL. 1 ‘ey‚"0 Ă˜Â‘ey‚" 1 ÂĽmk΂§0ÂĽmĂ˜Â‘ĂŽÂ‚" L 4.5-1: tkFont |Âą option

XĂšiNϴ Tk „|ÂąXĂš½Ă‚ iNœ¥§3X Windows e§Â˜Â„´Â?iNOϤXfixed, 6x10 " Windows e§ÂŒ¹´ansi, ansifixed, device, oemfixed, system, and systemfixed" 3Macintosh e§XĂšiNϴÂŒ¹´application and system" 5Âż XĂšiNœ¥´iN ¥§Â?)iNxϴĂšiNÂŒ §iNº‚"XJlÂŒ £‡5 Ă„ {§ Ă?Ă˜Â‡ÂŚ^ڍÂ?ÂŞ" X Font Descriptor X Font Descriptor ´Œ^e¥‚ª iĂŽG"(Ă’LÂŤ^%@Š" -*-family-weight-slant-*--*-size-*-*-*-*-charset family LÂŤiNx ϴ" weight ÂŒ¹´Bold ½ÜNormal" annCharles@tom.com

1181Â?, 208Â?

Python ÆS)P


o Tkinter ?§ slant ÂŒ¹´R LÂŤRoman § ~"½ÜI LÂŤ N"½ÜO LÂŤoblique § N˜ " size ´LÂŤiNÂŒ §ß ´point ›ŠÂƒÂ˜§Ă?~72 point = 1 inch charset LÂŤiĂŽ8§Ă?~´ISO8859-1" -*-Times-Bold-R-*--*-120-*-*-*-*-ISO8859-1 LÂŤ iN´12 point ÂŒ §\o Times iN§Œ^ISO Latin 1 ?è iĂŽ8" XJ\Ă˜'%, Š§@oĂ’^(ғO" ˜‡;. X Server Â˜Â„Ă‘|ÂąTimes, Helvetica, Courier, iN§ÂŒ ´8 , 10 , 12, 14, 18 , 24 . ÂŒ¹´\o§ N"ÂŒ¹Œ^xlsfonts Ăšxfontsel Unix ¡-5wÂŤiN" Windows ĂšMacintosh Â?|ÂąÂŒĂœŠÚ iN§ŒÂ‚ÂŹrڍLˆÂ?ÂŞÂ€Ăˆ¤Windows e½Macintosh Ăœ¡ iN"

§4.5.3 Ši‚ªz ˜„5`§Label ĂšButton Ă˜=|¹ß1Ši§Â„|¹þ1Ši"Ăľ1ŠiĂ’´ ^"\n" Š þ‡ß1Ši"%@Âœše§Ši´Ă˜¼Êà §ÂŒÂąUCjustify option Â?LEFT ½ÜRIGHT L†½ÜmĂŠĂ " Â„ÂŒÂą ˜wraplength option 5Â?½ ÂŒ Ă?§Ši Ă?XJ‡L ڇ ÂŒ Ă? Ă’gĆ1"

§4.5.4 >Âľ ÂŚ+k Widget >Âľ3%@ Âœše´wĂ˜ § ´¤k Widget Ă‘k˜‡> Âľ">ÂľÂ?)3D Relief( 2H) JĂšFocus Highlight( :pw)ÂŤÂ?" relief option ^ 5 L ÂŤ X Ă› Âą › ˜ ‡Widget > Âľ " ÂŒ Âą ´SUNKEN RAISED GROOVE RIDGE ĂšFLAT borderwidth ½ Ăśbd option L ÂŤwidget > Âľ ÂŒ § ˜ „´2 ½Ü1 § ÂŒ Ă’Ă˜Ă?w " Focus Highlight Region ( :p ÂŤ)Â?´Â˜ÂŤ>¾§´3>ÂľÂƒ ,˜‡>Âľ" 3widget Ă‘\ : žÿ§Â?Ă’´widget ÂŒÂą É^r Â… Ă‘\¯‡ žÿ§¹x ڇFocus Highlight Region §Â?Ă’´3>Âľ ÂĄ2x˜‡>¾§LÚ‡widget

:§ÂŒÂą Ʌ Ă‘\" highlightcolor option LÂŤwidget : žÿ§Focus Highlight Region Ă´Ăš§ ˜„´çĂš"highlightbackground option LÂŤwidget vk : žÿ§Focus Highlight Region Ă´Ăš§Â˜Â„Ăšwidget ˜ ¾Ú"highlightthickness LÂŤFocus Highlight Region °Ă?"˜„´1 ½Ü2 § ÂŒ Ă’Ă˜Ă?w " Ăšpk˜‡~f§^5`²>¾ÚFocus Highlight Region ^{" # border1.py annCharles@tom.com

1182Â?, 208Â?

Python ÆS)P


§4.5 Widget ÂŞ from Tkinter import * bd = range(1,9,3) t = [ "border = " + str(k) for k in bd ] relief= [ RAISED, SUNKEN,GROOVE ,RIDGE,FLAT] for i in range(len(bd)): for j in range(len(relief)) : Button(text=t[i]+" " + relief[j], relief=relief[j], highlightcolor = ’blue’, highlightbackground = ’white’, highlightthickness = bd[i], bd=bd[i]).grid( row=j, column=i, padx=2, sticky=W) mainloop() $1(JXĂŁ4-4"

ĂŁ 4-4: border1.py $1(J annCharles@tom.com

1183Â?, 208Â?

Python ÆS)P


o Tkinter ?§ highlightcolor Ăšhighlightbackground ¿‰¤Ă˜´AOĂ?w Ă´Ăš§4Ă–Ăś5Âż ÂŚ ‚ Cz"

§4.5.5 Ă I cursor option ÂŒÂąÂ?½Â˜Â‡Ă I/G§ Ă IÂŁĂ„ ڇwidget Ăž žÿ§wÂŤĂš ‡ Ă I/G"XJĂ˜Â?½Ú‡option §@o Ă IÂŁĂ„ widget Ăž žÿ§wÚŒ master widget cursor option ¤Â?½ Ă I/G" ”Text ĂšEntry Ăš widget §%@ UC Ă I/G§LÂŤI‡Ñ\Ši" eÂĄ ڇ~fߍ cursor option J" #!/usr/bin/env python cursors =["arrow", "based_arrow_down", "based_arrow_up", "boat", "bogosity", "bottom_left_corner", "bottom_right_corner", "bottom_side", "bottom_tee", "box_spiral", "center_ptr", "circle", "clock", "coffee_mug", "cross", "cross_reverse", "crosshair", "diamond_cross", "dot", "dotbox", "double_arrow", "draft_large", "draft_small", "draped_box", "exchange", "fleur", "gobbler", "gumby", "hand1", "hand2", "heart", "icon", "iron_cross", "left_ptr", "left_side", "left_tee", "leftbutton", "ll_angle", "lr_angle", "man", "middlebutton", "mouse", "pencil", "pirate", "plus", "question_arrow", "right_ptr", "right_side", "right_tee", "rightbutton", "rtl_logo", "sailboat", "sb_down_arrow", "sb_h_double_arrow", "sb_left_arrow", "sb_right_arrow", "sb_up_arrow", "sb_v_double_arrow", "shuttle", "sizing", "spider", "spraycan", "star", "target", "tcross", "top_left_arrow", "top_left_corner", "top_right_corner", "top_side", "top_tee", "trek", "ul_angle", "umbrella", "ur_angle", "watch", "xterm"] from Tkinter import * root = Tk() col=0; row = 0 for i in cursors: b=Button(text=i) b.grid( column=col,row=row, sticky=E+S+W+N) b.bind("<Motion>",lambda e,cur=i:root.config(cursor=cur)) col = col + 1 if col == 4 : row = row + 1 ; col = 0 annCharles@tom.com

1184Â?, 208Â?

Python ÆS)P


§4.5 Widget ª mainloop() $1(JXã4-5"

ĂŁ 4-5: cursor1.py $1(J

Ă IÂŁĂ„ zÂ˜Â‡Ă˜Ă“ UĂœÞ§à I /GĂ’ÂŹC¤Ă˜Ă“ /G" annCharles@tom.com

1185Â?, 208Â?

Python ÆS)P


o Tkinter ?§

§4.6 ¯‡Ú¯‡ Â?½ Â&#x;o´¯Â‡§^rÂŒUÂŁĂ„Ă I§½ÜU ˜‡…§Ú Ă‘´¯Â‡§¯Â‡Â„Â?)WM ‡Œwidget ­xgC ¯‡"ĂŠĂľwidget Ă‘ÂŒÂą ɯ‡§¿Â…N^ƒA ?nŸê"ò ¯‡Ú´¯Â‡?nŸêÊX Â˜ĂĽ Â?{Ă’´N^ w.bind(event,handler) w ´Â˜Â‡widget, event ´Â˜Â‡iĂŽG§^uL㯇§handler ´Â˜Â‡callable ĂŠ –§^u?n¯‡§Â?Ă’´`§3¯‡u) žÿ§N^ڇʖ§Ă“žD4Â˜Â‡ĂŤ ê§^u£ã¯‡"

§4.6.1 ˜‡{Ăź ~f # File: bind1.py from Tkinter import * root = Tk() def callback(event): print "clicked at", event.x, event.y def test(e): D = vars(e); for k in D: print "%-10s:%s"%(k,D[k]) frame = Frame(root, width=100, height=100) frame.bind("<Button-1>", callback) root.bind("<Control-Alt-Key-colon>",test); frame.pack(expand=1,fill=BOTH) frame.focus_set() root.mainloop() ڇ§SrßÂà I†… ¯‡Úcallback ڇŸê”½3˜ü§Â”½ ÂżgĂ’´` )ڇ,‡¯‡ žÿ§Ă’N^ƒA ?nŸê" XJ,‡¯‡u) §Ă“ž‰1 ƒA ?nŸê§¡Â‚ÂĄÂ?Ă“Âź ڇ¯‡" $1ڇ§S§XJ3Frame ÞßĂ‚Ă I§Ă’ÂŹ3›› ދ<Ă I ‹I"XJĂ“ žUeControl §Alt §ĂškĂ’§Ă’‹<¯‡ ¤k&E" £ã¯‡ Â?ÂŞ ĂžÂ˜Â‡~f¼§â€?ÂĄButton-1Âżâ€? ÂŁĂŁĂ I߆… ¯‡§£ã¯Â‡ ‚ªXe: <modifier-modifier-type-detail> annCharles@tom.com

1186Â?, 208Â?

Python ÆS)P


§4.6 ¯‡Ú¯‡ Â?½ 0 Ă I Â…½Ă‚3X windows ÂĽÂ˜ k5 ‡à IÂ… ½Ă‚§Â˜Â„´ 1 3 5

†… m… EœeE

2 4

ÂĽÂ… EœÞE

˜„Â?^1 , 2 , 3 n‡…" ´Ă˜ ´Â˜¤Ă˜C §ÂŒÂą^xmodmap ¡-UC" xmodmap -pp ÂŒÂąw cĂ IUÂ… ½Ă‚" 3 wu)Â&#x;o¯‡ žÿ§¹eóä´Êk^ " xmodmap xev

wÚ?UX … N 'XÚà IN 'X" ^5 w¯‡ "

modifier LÂŤu)Ă I½ÜÂ… ¯‡ žÿ§Ă“žUe ٌ…§Xcontrol §alt §win(super) Â… §½ÜÂ˜Â‡ÂŻÂ‡3åžmS­EĂľg" modifier ÂŒ¹´ Control Shift Lock Button1, B1 Button2, B2 Button3, B3 Button4, B4 Button5, B5 Mod1, M1

Mod2, M2 Mod3, M3 Mod4, M4 Mod5, M5 Meta, M Alt Double Triple Quadruple

B1 LÂŤu)Â… ¯‡ žÿ§à I †…´?uUe G " Meta ĂšAlt Ă‘´ÂŒÂąĂ?Lxmodmap UCN 'X "äN´=Â˜Â‡Â…ĂšX XĂš ˜ k'X" ÂŒÂąÂ?½þ‡modifier §^~Ă’Š "X <Control-Alt-Key-colon> Ù¼Control §Alt ´modifier §Key ´type §colon ´detail § ‡¯‡£ãLÓž UeControl Alt ĂškĂ’§Â?Ă’´`ӞUeControl Alt Shift ĂšŠĂ’§Ă?Â?ӞUeShift ĂšŠĂ’§LÂŤkĂ’" Double ^uÂŁĂŁĂ IV¯‡" type ´  ­ ‡ § § ½ Ă‚ ¡ ‚ ” ½ = ˜ ÂŤ ÂŻ ‡ " ˜ „ ´ButtonPress §ButtonRelease ½Ü´KeyPress §KeyRelease §Â?ÂŒ¹´Ă™ÂŚ Š§ÂŒÂąĂ?L annCharles@tom.com

1187Â?, 208Â?

Python ÆS)P


o Tkinter ?§ man -S n bind w¤k¯‡a." type ´ButtonPress ĂšButton Release žÿ§detail ÂŒ¹´1, 2, 3, 4, 5 ^uLÂŤĂ IÂ…§XJĂ˜Â?½detail §LÂŤU?ۅ" 5¿à IU…ŠÂ?modifier Ăštype ÂŤO§Â?Ă’´<Button1> Ăš<Button-1> ÂŤO" cĂśLÂŤ ,¯‡u) žÿ§à I ,‡UÂ…?3Ue G " ĂśLÂŤu) Ă IU Â… ¯‡" type ´Motion ž Ăż § L ÂŤ Ă I ÂŁ Ă„ ÂŻ ‡ " ˜ „ Â? ½B1 modifier" X<B1-Motion> LÂŤĂ I†…Ue¿…£Äà I"XJĂ˜Â?½modifier §@oL¤k Ă I£Ä¯‡" XJtype ´KeyPress ½ÜKeyRelease §@odetail ^5Â?½ .´=˜‡… UÂ…" äN ÂŠÂŒÂą wkeysyms Â?Ă?" man keysyms keysyms ´Â˜Â‡ÂŒÂ‹< ASCII iĂŽ§½ÜÂ˜Â‡Ă˜ÂŒÂ‹< ASCII iĂŽ £ã§Â„ ÂŒ¹´ÂšASCII iĂŽ ÂŁĂŁ" ߇k^  "<1> <2> <3> ŠOLÂŤĂ I†…§¼Â…§mÂ… UÂ… ¯‡"<a> <b> <c> ... LÂŤUea, b, c iĂŽ ¯‡" ¯‡£ãÞ~§XL4.6-2Âľ

§4.6.2 ¯‡?nŸê u)¯‡ žÿ§N^¯‡ ?nŸê§D4Â˜Â‡ĂŤĂŞevent §^u£ã¯‡u) žÿ &E"^eÂĄ “èÂŒÂąÂ‹<¤k&E" def test(event): D = vars(event); for k in D: print "%-10s:%s"%(k,D[k]) äNĂŤĂŞXeL4.6-3

§4.6.3 ¯‡

g

Ă“Â˜Â‡ÂŻÂ‡ÂŒÂąkþ‡¯‡?nŸê§Ú ?nŸêåuĂ˜Ă“ Âąkþ‡¯‡?nŸê?nĂ“Â˜Â‡ÂŻÂ‡" ÂŒÂą3oÂ‡Ă˜Ă“

g"z˜‡

g„Œ

g¼”½¯Â‡"

• widget instance ? Â?½,˜‡widget instance ¯‡”½"Â?k3¯‡u)3,˜‡Â?½ widget ž ÿ§âĂ“Ÿ¯Â‡"”½Â?{´w.bind(...) §w ´Â˜Â‡widget instance " annCharles@tom.com

1188Â?, 208Â?

Python ÆS)P


§4.6 ¯‡Ú¯‡ Â?½

<Button-1> ½<1> <B1-Motion> <ButtonRelease-1> <Double-Button-1> <Enter> <Leave> <Return>

<Key> a <Shift-Up> <Configure>

UeĂ I†… UeĂ I†…Óž£Äà I" ÂşÂ˜Ă I†…" 3ĂŠĂĄ žmS(š~¯„ )§à IÂŁĂ„Â?3ĂŠ ‰ŒS(A vkÂŁĂ„)§ÍYUeĂźgĂ I†…" Ă IÂŁĂ„ Widget ‰ŒƒS"5ÂżĂ˜´Ue

Â… ÂŁÂ?Â…§Enter L¯‡ type " Ă IlmWidget ‰ŒƒS" Ue Â… ÂŁÂ?Â…"´Â˜Â‡{ §L ÂŤ<KeyPress-Return> "3keysyms Â?Ă?ÂĽÂŒÂą A ¤k š‹<iĂŽ ÂŁĂŁ" Ue ?Ă› Â… " LÂŤUe Â… “aâ€? Â…" LÂŤU4Â… Shift Â…Ă˜Â˜ Ӟ§Ue Â?•…¼ ޅ" LÂŤWidget ÂŒ u)UC žÿ ¯‡" L 4.6-2: ¯‡£ãÞ~

widget x,y x root, y root char keysym num wight, height type

)¯‡ widget §¤k ¯‡event Ă‘ÂŹ Â˜ĂšÂ‡ ĂĄ5" LÂŤu)¯‡ žÿ§à I3widget ÂĽ ÂƒĂŠÂ Â˜" ß ´pixel LÂŤĂ I3Âś4ÂĽ ÂƒĂŠÂ Â˜" a.´string §LÚ… k' ¯‡¼§äNUe ´=˜‡ iĂŽè" 3څ k' ¯‡¼§LÂŤUÂ… ŠiÂŁĂŁ" 3Úà Ik' ¯‡¼§LÂŤĂ IUÂ…" LÂŤwidget # ÂŒ "Â?3configure ¯‡¼k " L¯‡ a." L 4.6-3: £ã¯‡ ĂŤĂŞ

annCharles@tom.com

1189Â?, 208Â?

Python ÆS)P


o Tkinter ?§ • IÂ?? widget ¤ ĂĄ Toplevel ĂŠ – ½ Ăśroot ĂŠ – § ½ Ăś ` I Â? ? § Â? ” ½ Â? { ´root.bind(...) ½Ütop.bind(...) root Ăštop ŠOLÂŤToplevel ʖÚroot ĂŠ –" • widget class ? ÂŚ^bind_class §L¤kÂ?½class instance Ă‘ÂŹkÂ˜Â‡ÂŻÂ‡Â”½" • A^§S? ?Ă›/Â?u)¯‡§Ă‘ÂŹĂ“Âź"ÂŚ^bind_all " ~XÂŚ^bind_all ”½F1 Â…§Ú ĂƒĂ˜3?Ă›/Â?§Â?‡U F1 …ҏ‰1Â?Ă?§ S" ´XJĂ“Â˜Â‡ÂŻÂ‡3Ă˜Ă“ gޔºþg žÿ§TNoÂ?Q? ½Ü`Â˜Â‡ÂŻÂ‡­ U ”½ žÿ§TNoÂ?ÂşÂ&#x;o´­U”½QÂş~X§¡Ă“ž”½ <Key> Ăš<Return> ¯‡§Â˜Â‡LÂŤUe?¿…§Â˜Â‡LÂŤUeÂŁÂ?Â… ¯‡§<Return> ¯‡ÓžÂ?´Â˜ ‡<Key> ¯‡§ÚĂ’´­U”½" Ă„k§Â˜Â‡ÂŻÂ‡u) žÿ§Tkinter 3z˜‡ gÞ§Ă?ĂŠÂ˜Â‡ ÂƒC ¯‡” ½"~X§XJUe ÂŁÂ?Â…§<Return> ¯‡'<Key> ¯‡Â?C"<Return> ¯‡ Ă“ ٤<Key> ¯‡KĂ˜ÂŹ Ă“Âź" Â?Ă’´`§­UÂŻÂ‡Âƒß½§ C ¯‡ Ă“Âź" ^aqêÆ Šó£ãĂ’´§zÂ˜Â‡ÂŻÂ‡ÂŁĂŁĂ‘Â˜Â‡ÂŻÂ‡ 8Ăœ§8ĂœÂĽ ƒ´Â˜ ‡¯‡§XJ˜‡8ĂœA ´,˜‡8ĂœB f8§@o`ڇA 'B " ¯‡u) ž ÿ§@oĂ’3z˜‡ gĂžĂ?ĂŠÂ?šT¯‡  8Ăœ§, 2z˜‡ gÞӟT¯‡" XJ3widget instance g”½ <key> ¯‡§3toplevel ޔ½ <Return> ¯‡§ @o UeÂŁÂ?Â… žÿ§Ú‡¯‡3߇ gÞя Ă“Âź" Ú´Ă?Â?ÚßÂ‡ÂŻÂ‡Ă˜´­U¯‡§ ´3Ă˜Ă“ gĂž ¯‡§­U¯‡´½Ă‚3Ă“Â˜ gĂž Vg§Â?Ă’´`§­U¯‡Ñ´3Ă“Â˜ gĂž " Tkinter Ă„k3widget instance gÞÓŸ¯Â‡§Â‰1¯‡?nŸê§, Â?g 3widget class gÞ§Toplevel gÞ§A^§S?Þ§ŠOĂ“Ÿ¯Â‡"ڇÓŸ¯ ‡ ^Sʭ‡" Â?Ă’´`§Ă˜Ă“

gÞ ¯‡U^Sӟ"

§Sbind level.py ĂŠĂ? `² ĂšÂ˜:" # File: bind_level.py from Tkinter import * root = Tk() def callback(event): annCharles@tom.com

1190Â?, 208Â?

Python ÆS)P


§4.6 ¯‡Ú¯‡ Â?½ print "clicked at", event.x, event.y def test(e): print "you press: " + e.keysym return def application_level_bind(e): print "application level binding" test(e) def class_level_bind(e): print "class level bind " test(e) def toplevel_bind(e): print "top level bind" test(e) def widget_level_bind(e): print "widget instance level bind" test(e) def myprint(a): print a frame = Frame(root, width=100, height=100) root.bind("<Key>", toplevel_bind) root.bind_class("Frame","<Key>",class_level_bind) root.bind_all("<Key>",application_level_bind) frame.bind("<Key>", widget_level_bind) frame.bind("<Return>", lambda e: myprint("RETURN PRESSED") ) frame.pack(expand=1,fill=BOTH) frame.focus_set() root.mainloop()

§4.6.4 Ă“Â˜Â‡ÂŻÂ‡ þ‡?nŸê Ă“Â˜Â‡ÂŻÂ‡ÂŒÂąk߇¹Þ ¯‡?nŸê"bind(e,func) Ÿê%@ Ċ´^Â?½ ¯‡?nŸêfunc “O¤k k ¯‡?nŸê" ´XJÂ?½1n‡ÍêÂ?“addâ€? ~X: bind(e,func,"add") Ă’ÂŒÂą 3 5 ¯‡?nŸê§Â?Ă’´3Â˜Â‡ÂŻÂ‡?nŸêó  O\˜‡?nŸê" Â˜Â‡ÂŻÂ‡u) žÿ§Ă’ÂŹÂ?d‰1¯‡?nŸêóÞ zÂ˜Â‡ÂŻÂ‡?nŸê"XJ=˜ ‡ŸêÂˆÂŁ ˜‡iĂŽG“breakâ€? @oҏʎ‰1 ÂĄ ¯‡?nŸê§Ă“žÂ?ĂŠÂŽN^ annCharles@tom.com

1191Â?, 208Â?

Python ÆS)P


o Tkinter ?§ ٌ g ¯‡?nŸê" ~fchange text bind.py `² ڇ¯K" # change_text_bind.py from Tkinter import * def ignore (e): return "break" def ignore2(e): print "you can only input one line" root = Tk() t = Text() t.bind("<Return>",ignore2) t.bind("<Return>",ignore,"add") t.pack(fill=BOTH,expand=1) root.mainloop() ڇ~fÂŽ?U˜‡Text widget %@ ¯‡”½§3%@ Âœše§UeÂŁÂ?Â…LÂŤ Ă‘\# ˜1§XJ==”½ignore2 ´Ă˜1 §Œ+O“ instance ?OĂž ”½'X§ ´<Return> ¯‡ ?n´class ?OĂž §¤¹Â„Ă˜vÂąUC%@܊§^r„´ÂŒÂąĂ‘ \# ˜1"¤¹O\ignore ”½§4ÂŚÂƒä¯Â‡?nŸê UY‰1§Ú âUˆ 8 " ,§3ignore2 ÂĽÂˆÂŁâ€œbreakâ€? Â?´ÂŒÂą " XJ¯‡?nŸêó¼k˜‡ŸêÂˆÂŁ “breakâ€? @o2O\?nŸê´vk¿Â " „kÂ˜ÂŤÂ?{ÂŒÂąÂ‰ § root.bind_class("Text","<Return",ignore) ´Ú ‰k˜‡":§\§S¼¤k Text widget Ă‘Ă˜UĂ‘Ă‘\# ˜1 ")Ăť Â? {Ă’´§MĂŻÂ˜Â‡# a§UÂŤText §, 3?U#a ¯‡”½'X"

§4.6.5 ĂšWM ƒ' ¯‡”½ u)ĂšWM ƒ' ¯‡ žÿ§~X§S  z(q ĂŁIz)§ ÂŒz§'4§ ÂŁĂ„ " ~^ ¯‡Ò´WM_DELETE_WINDOW LÂŤ^rÂŚ^WM 5'4IÂ? ¯‡" ‡”½Ú˜a¯‡ Â?{´ w.protocol("WM_DELETE_WINDOW",handler) w ´Â˜Â‡widget ʖ§handle ´¯Â‡?nŸê§Ă˜D4?ÛÍê" weÂĄ ~f: from Tkinter import * from tkMessageBox import askokcancel annCharles@tom.com

1192Â?, 208Â?

Python ÆS)P


§4.7 ~^ A^§SŒ^ Widget

def handler(): if askokcancel("Quit","Do you really want to exit?"): root.destroy() root=Tk() root.protocol("WM_DELETE_WINDOW",handler) root.mainloop() ˜„œše´Ă˜^Ăš ”½ §Ă?Â?§z˜‡IÂ??nWM_DELETE_WINDOW ¯‡ %@ ĊÒ´N^destroy Ÿê5'4gC" ٌ aqWM_DELETE_WINDOW ÂŻÂ‡ÂŒÂą wICCCM(Inter-Client Communication Conventions Manual) Š §

§4.7 ~^ A^§SÂŚ^ Widget §4.7.1 Ă„ IÂ? ¡Â‚Ž²^L §root=Tk() Ă’ÂŹMĂŻÂ˜Â‡root window §Ú‡IÂ? '4 §@oĂ’ '4¤k Ă™§IÂ?§§SòĂ‘" MĂŻÂ˜Â‡Toplevel ʖ§Ă’ÂŒÂąMïٌ IÂ?§Ú IÂ?'4§Ă˜òĂ‘§S§Ă™§ Â?ÂĄToplevel Ăšroot window ´Â›Šaq " Toplevel Ă˜Â”Ă™ÂŚ Widget §Ă˜^pack ½Ügrid §ŒĂ’ÂŒÂąwÂŤĂ‘5§Ă?Â?§´Â˜Â‡ IÂ?§WM ÂŹwÂŤÂŚ " z‡IÂ? %@IK´â€œTkâ€? §UCIÂ? IK^ root.Title("My title") ˜‡IÂ? IK Â?{´ print root.Title()

§4.7.2 èß ~fmenubar2.py ›Šèß9 ˜‡~f" # menubar2.py from Tkinter import * import sys root = Tk()

annCharles@tom.com

1193Â?, 208Â?

Python ÆS)P


o Tkinter ?§ mainmenu=Menu(root) root["menu"]=mainmenu filemenu = Menu(mainmenu) mainmenu.add_cascade(label=’file’,menu=filemenu) m = [ "new","open","save"] for i in m : filemenu.add_command( label=i, command=lambda t = i: sys.stdout.write(t+"\n") ) filemenu.add_command(label="exit", command= root.quit) mainloop() $1(JXĂŁ4-6 5¿§¯Â‡?nŸê E|§

ĂŁ 4-6: menubar2.py $1(J

lambda : sys.stdout.write(i) ´Ă˜1 " Ă?Â?z˜‡èß ?nŸêĂ‘´Â˜ §Ă‘´Â‹<i Š§Â&#x;ožÿ\UC i Š§ ‹< (JĂ’ÂŹC" lambda t = i : sys.stdout.write(i) annCharles@tom.com

1194Â?, 208Â?

Python ÆS)P


§4.7 ~^ A^§SÂŚ^ Widget KĂ˜Ă“§z˜‡èß ?nŸê´Ă˜Â˜ §ŒÂ‚ %@ĂŤĂŞĂ˜Ă“§%@ĂŤĂŞ DŠ´3Âź ĂŞMĂŻ žÿ" ÂŒÂąw lambda MïŸê Â?Bƒ?§ÂŒÂą^ڍÂ?{§Â?, ¯‡?nŸêO\% @ĂŤĂŞ"Ăš Â˜Â‡ÂŻÂ‡?nŸêÂŒÂą?nþ‡widget ) ¯‡§~ Ÿê êÞ§ÂŒÂą{ z O§Â?B‘o" U^Â?{ĂźÂ? ŠÊ ¤Ă“ ĂľU§Ú §Sâ´Ă?§S" „kÂ˜ÂŤÂ‰{§Œ^Menubutton ~fmenubar3.py ›Šèß9 ˜‡~f" # menubar3.py from Tkinter import * import sys root = Tk() # create a frame to contain the menu bar menuframe = Frame() # create a menu button filemenuButton = Menubutton(text="File") filemenuButton.pack(side=LEFT,anchor=N) # create the "file" menu filemenu = Menu(filemenuButton) # connect the filemenu with hte filemenuButton filemenuButton[’menu’]=filemenu m = [ "new","open","save"] for i in m : filemenu.add_command(label=i, command= lambda t = i: sys.stdout.write(t+"\n") ) filemenu.add_command(label="exit", command= root.quit) menuframe.pack(side=TOP,fill=X,expand=1) mainloop() $1(JXĂŁ4-7 Ăź ‡ ~ f „ ´ k ÂŤ O "Menubutton ´ ˜ ‡ ĂšButton a q Ă€ Ăœ § ´ ÂŚ % @ command Ċ´ Ă˜Â˜Â‡èß" ÂŚ^Menubutton kÂąeA‡Ú½: 1. ĂŻĂĄMenubutton. mb = Menubutton() annCharles@tom.com

1195Â?, 208Â?

Python ÆS)P


o Tkinter ?§

ĂŁ 4-7: menubar3.py $1(J 2. 3ŒÞ¥wÂŤÂ˜Â‡Ă? SN§JÂŤ^r" mb["text"]="press me" 3. MĂŻÂ˜Â‡Menu §Œ master widget ´mb m = Menu(mb) 4. rMĂŻ Menu ĂšMenubutton ĂŠX3Â˜ĂĽ" mb["menu"] = m 5. O\menu SN m.add_command(label="new", command=lambda : sys.stdout.write("Hello Menu\n") 6. wÂŤMenubutton mb.pack() XJ‡3menu ĂžO\˜‡Š ‚§^ m.add_separator() XJ‡3menu ĂžO\˜‡fèߧ^ submenu = Menu(m) # 5Âż master widget ˜½Â‡´Ièß" m.add_cascade(menu=submenu,label="a submenu") annCharles@tom.com

1196Â?, 208Â?

Python ÆS)P


§4.7 ~^ A^§SŒ^ Widget

§4.7.3 óä9 ĂŠĂľA^§SĂ‘k˜‡óä9"Ă™¢Â˜Â‡óä9Ă’´Â˜Â‡Frame §Ă™ÂĽÂ?š ĂŠĂľ Button" žw~ftoolbar.py " # toolbar1.py from Tkinter import * root = Tk() def callback(): print "called the callback!" x = ["error", "gray12", "gray25", "gray50", "gray75", "hourglass", "info", "question", "warning"] # create a toolbar toolbar = Frame(root) for i in x : b = Button(toolbar, text=i, bitmap=i, command=lambda t=i: sys.stdout.write("%s\n"%t) ) b.pack(side=LEFT, padx=2, pady=2,fill=BOTH,expand=1) toolbar.pack(side=TOP, fill=X) mainloop() $1(JXĂŁ4-8 z˜‡Button Ă‘Þ¥kÂ˜Â‡ĂŁI§Â˜Â˜ Â?ª´¾Â‚†˜§gĂ„UCÂŒ §UC ÂŒ žÿ3X Y Â?•ÞыXÂ˜ĂĽUCButton ÂŒ §Þe†mĂ‘3Ă‘52 ‡”ƒ ˜ Y" toolbar ˜˜Â?ª´: Â‚ĂžÂ˜§3X Â?•ÞgĂ„UCÂŒ " Ă˜ ÂŚ^bitmap otption Â˜Â˜ĂŁIƒ §Â„ÂŒÂąUCimage option 5wÂŤĂŁI§ÚI‡ ÂŚ^PhotoImage MĂŻÂ˜Â‡ĂŁÂ”"

§4.7.4 G 9 Êþ§S eÂ?Ă‘k˜‡G 9§Ă™¢Â?´Â˜Â‡Frame Ă™¼šk˜‡½Üþ‡Label § annCharles@tom.com

1197Â?, 208Â?

Python ÆS)P


o Tkinter ?§

ĂŁ 4-8: toolbar1.py $1(J

ÂŒÂągC ˜‡§S§Â?Ă˜J" žw~fstatusbar.py " # toolbar1.py from Tkinter import * root = Tk() def callback(): print "called the callback!" x = ["error", "gray12", "gray25", "gray50", "gray75", "hourglass", "info", "question", "warning"] # create a toolbar toolbar = Frame(root) for i in x : b = Button(toolbar, text=i, bitmap=i, command=lambda t=i: sys.stdout.write("%s\n"%t) ) annCharles@tom.com

1198Â?, 208Â?

Python ÆS)P


§4.7 ~^ A^§SŒ^ Widget b.pack(side=LEFT, padx=2, pady=2,fill=BOTH,expand=1) toolbar.pack(side=TOP, fill=X) mainloop() Œ^ tkSimpleStatus.py " # File: tkSimpleStatusBar.py from Tkinter import * class StatusBar(Frame): def __init__(self, master): Frame.__init__(self, master) self.label = Label(self, bd=1, relief=SUNKEN, anchor=W) self.label.pack(fill=X) def set(self, format): self.label.config(text=format) self.label.update_idletasks() def clear(self): self.label.config(text="") self.label.update_idletasks() $1(JXã4-9

ĂŁ 4-9: statusbar1.py $1(J ڇ~fÂĽÂ?k˜‡wÂŤ9§ÊN´O\˜‡wÂŤ9§ĂƒÂšĂ’´O\˜‡Label "

§4.7.5 IOĂŠ{Âľ XJĂ’´ {Ăź Ă‘\&E§XÂ˜Â‡ĂŞi§Â˜Â‡iĂŽG§£Â‰´Â„´Ă˜´§ ˜‡ annCharles@tom.com

1199Â?, 208Â?

Python ÆS)P


o Tkinter ?§ ŠÂ‡œ¥§ ˜‡iNœ¥§ Â˜Â‡Ă´Ăš §ky¤ {ĂźIOĂ‘\Âľ"ĂŠĂ?^" {Ăź žEÂľ tkMessageBox ÂŹJø ÊþŸê§^5MĂŻÂ˜Â‡{Ăź žEÂľ" ´Â‡5¿§Ă˜UE^žE¾§Windows e §SĂ’²~ Ă‘Â˜Â‡ÂžE¾§¯¡Â‡Ă˜ ‡ §Â‡Ă˜Â‡Ă˝ òĂ‘§ r^r ¤ä §Â˜Â‡Ă? Â?{´1˜g Ă‘5ĂŠ{¾§ ^r AT %§Ă“ž^rÂŒÂąĂ€JÂą Ă˜Â‡2 Ă‘5Ăš ĂŠ{Âľ " ÂŒÂąw˜etkMessageBox.py §S§å h<§vÂŽ ĂšoĂĄ §SÂŒÂą ¤Úo Ăľ ÂŻÂœ§Œ+ÂŒþê¯ÂœĂ‘´Tk ‰ " ÂŒÂą$1 python

/usr/lib/python2.2/lib-tk/tkMessageBox.py

w ÂŚ ÿà §S" ڇ ÂŹJø ˜eŸê: showinfo, showwarning, showerror, askquestion, askokcancel, askyesno, Ăš askretryignore. Œ‚ N^Â?{Ă‘Â˜ " tkMessageBox.function(title, message [, options]). title ´IK"message ´Â‡w‰^r &E" option kÂąe Ă€J: default

icon message parent title type

ÂŒ¹´ABORT, RETRY, IGNORE, OK, CANCEL, YES, ½ÜNO LÂŤ%@ ^‡e§=˜‡UĂœ :" LÂŤÂŚ^Â&#x;o IOĂŁI"ÂŒ¹´ERROR, INFO, QUESTION, WARNING Ăš1 ‡Íêmessage ´Â˜Â‡Âżg" LÂŤĂŠ{Âľ(ĂĽÂƒ §=˜‡IÂ?C¤ cIÂ?" Ăš1Â˜Â‡ĂŤĂŞtitle ´Â˜Â‡Âżg" wÂŤ=˜aUĂœ§ÂŒ¹´ABORTRETRYIGNORE, OK, OKCANCEL, RETRYCANCEL, YESNO, YESNOCANCEL"l “èÂŒÂąw §z˜‡Ÿê Ž²%@ Ă? type §Ú Ă??´Jp§S ÂŒ Ă–5"

annCharles@tom.com

1200Â?, 208Â?

Python ÆS)P


§4.7 ~^ A^§SÂŚ^ Widget {ßêâĂ‘\

3tkSimpleDialg ¼§Jø Â˜Â‡Ă‘\{ßêâ {ßÊ{Âľ"

tkSimpleDialog.askstring(title, prompt,[options])

ÂŒÂąÂˆÂŁÂ˜Â‡iĂŽG§XU Cancel UĂœ§@oÂˆÂŁNone Ù¼¾ title prompt options initialvalue parent

LÂŤIÂ? IK" LÂŤJÂŤ^rĂ‘\&E Ši" ÂŒ¹´¹eĂ€J" LÂŤĂ?ŠÂŠ´Â&#x;o" LÂŤ^rĂ‘\ . §wÂŤ=˜‡IÂ?"

„kaq tkSimpleDialog.askinteger ĂštkSimpleDialog.askfloat ^{ĂšÞ¥ ˜ § XJ^rU Cancel §@oÂˆÂŁNone Ú߇Ÿê„k߇option ÂŒÂąĂ€J"minvalue Ăšmaxvalue ŠOLÂŤÂ ÂŒ ÂŠ§^u Â›^r3˜½Â‰ÂŒSĂ‘\êŠ" ‹mŠÂ‡ ĂŠ{Âľ

tkFileDialog ÂŹJø ߇Ÿê:

tkFileDialog.askopenfilename tkFileDialog.asksavefilename ÂŒÂąÂˆÂŁÂ˜Â‡ŠÂ‡ĂŠÂ–§XJ^rU Cancel @oÂˆÂŁNone " ÂŚ^Â?{´:

tkFileDialog.askopenfilename(options) tkFileDialog.asksavefilename(options) ÂŒ¹Œ^ option k: annCharles@tom.com

1201Â?, 208Â?

Python ÆS)P


o Tkinter ?§ œ¥ defaultextension

a. string

filetypes

list

initialdir initialfile parent title

string string widget string

ÂŁĂŁ XJ^rvk‰ÑŠÂ‡ * Ă?Ϥ@oĂ’gĂ„\ÞÚ‡ *Ă?ϴ" list ÂĽ z ˜ ‡ ƒ ´ ˜ ‡(label,pattern) tuple " c ÂĄ label ^ u J ÂŤ ^ r´Â&#x;o a. Š ‡§pattern ^uš ŠÂ‡Âś ÂĄ" Ă?Š8š" %@ŠÂ‡ϴ" Ă“Ăž" IÂ?IK"

~X: openfile(filetypes=[("text file","*.txt")]) ‹mÂ˜Â‡ĂŠ{¾§JÂŤ^r‹mŠ ŠÂ‡§Â?Ă’´¹txt (— ŠÂ‡" Ă€JĂ´Ăš ĂŠ{Âľ tkColorChooser ÂŹJø ˜‡askcolor Ÿê^uJÂŤ^rĂ‘\Â˜Â‡Ă´ĂšÂŠ"ÂŚ^Â? {´: askcolor([color[,options]]) ÂŒ^ options Xe: color

parent title

LÂŤÂ˜Â‡Ă´ĂšÂŠ§ÂŒ¹´Â˜Â‡iĂŽG§Â„ĂŒĂ´Ăš½Ă‚ ‚ª§7L´â€œ#rgbâ€? “#rrggbbâ€? “#rrrrggggbbbbâ€? ‚ª"Â?ÂŒ¹´Â˜Â‡tuple Ă™¼škn‡ ƒ§Š OLÂŤRGB nÂ‡Ă˜Ă“ŠÞ"ڇôڊÚ1˜‡ Íê´Â˜Â‡Âżg§Â?² Ă?Šôڊ" Ă“Ăž" IÂ?IK"

ÂˆÂŁÂŠ´Â˜Â‡tuple§Ă™ÂĽk߇ ƒ§1˜‡´^tuple LÂˆĂ´Ăš Â?ª§1 ‡´^ iĂŽGLÂˆĂ´Ăš Â?ÂŞ" g½Ă‚ĂŠ{Âľ x ¹ÞÊ{ÂľĂ˜áv‡Œ žÿ§ÂŒ¹Œ^tkSimpleDialog ÂŹÂĽJø Dialog a" ÂŒÂą wtkSimpleDialog.py “è§Â?Ă˜´AOE," annCharles@tom.com

1202Â?, 208Â?

Python ÆS)P


§4.7 ~^ A^§SÂŚ^ Widget ÂŚ^Â?{ĂŠ{Ăź"Dialog aUÂŤ Toplevel §¤¹ŒÂ?´Â˜Â‡IÂ?ʖ" weÂĄ ~finputpassword.py #inputpassword.py from Tkinter import * from tkSimpleDialog import * class DlgInputPassword(Dialog): def body(self,master): Label(master,text="user name:").grid(row=0,column=0) Label(master,text="password :").grid(row=1,column=0) self.username = Entry(master) self.username.grid(row=0,column=1) self.password = Entry(master) self.password.grid(row=1,column=1) def apply(self): self.result = self.username.get() , self.password.get() def validate(self): return 0 root = Tk() d=DlgInputPassword(root) print d.result $1(JXĂŁ4-10

ĂŁ 4-10: inputpassword.py $1(J Ă™¼­ body Ÿê§Ăšapply Ÿê"k Ú߇ŸêĂ’ÂŒÂą ¤Â˜Â„ĂľU ܊

"body Ÿê^5MĂŻĂŠ{¾¼ z˜‡widget § ´Ă˜Â?šOK ĂšCancel UĂœ" annCharles@tom.com

1203Â?, 208Â?

Python ÆS)P


o Tkinter ?§ apply Ÿê^uÂˆÂŁk^ Š§Â˜Â„ ˜self.result ĂĄ5§^uÂˆÂŁ&E" 3^rU OK UĂœ žÿ§Ă’ÂŹN^apply Ÿê ˜self.result "XJU Cancel U Ăœ§self.result Ă’´None " „k˜‡Ÿêvalidate()ÂŒ¹­ "vk?ÛÍê"validate() ڇŸê^5 ä^rĂ‘ \ &E´Ă„ávÂ‡Τ ^rU OK UĂœ žÿ§Ă’ÂŹgĂ„N^ڇŸê§XJڇŸ ĂŞÂˆÂŁ1 §LÂŤ^rĂ‘\´ávĂœ6‡Œ §Ă’N^apply ˜self.result , ÂˆÂŁ"XJĂš ‡ŸêÂˆÂŁ0§U OK Â?Ă˜ĂĽÂŠ^" Ă?‰^r˜‡J§wŠ^rÂ?Â&#x;oĂ˜U ~ ò Ă‘" „k˜‡buttonbox ŸêÂŒ¹­ "Â?´vkĂľ{ ĂŤĂŞ"ڇŸê %@Ċ´MĂŻ ߇UĂœ§Â˜Â‡´OK ˜‡´Cancel "U ڇŸêÂŒÂąMĂŻ^rgCŽ‡ UĂœ/ª§ %@ ߇UĂœ"Ӟ§rOK UĂœ ?nŸêĂšself.ok ”½§Cancel UĂœ ?nŸê Ăšself.cancel ”½"self.ok Ăšself.cancel ´ß‡Ž² Ă? %@Ÿê" wtkSimpleDialog.py ÂŹ Â?Ăľ &E"

annCharles@tom.com

1204Â?, 208Â?

Python ÆS)P


1ĂŠĂ™

Python * Ă? §5.1 ^C? *Ă? ÂŹ ^C Šó? *Ă?´ÊÂŒ ˜‡K8"kއ~f" $ls # c8šÂ?k˜‡ demo.c spammodule.c $cat spammodule.c #include <Python.h> /*7L‡\\ ĂžŠÂ‡*/ static PyObject * /*¤k PythonʖÑ´Ú‡a..*/ spam_system(PyObject * self, PyObject * args) { char *command; int sts; if (!PyArg_ParseTuple(args, "s", &command)) return NULL; sts = system(command); return Py_BuildValue("i", sts); } static PyMethodDef SpamMethods[] = { {"system", spam_system, METH_VARARGS, "Execute a shell command."}, {NULL, NULL, 0, NULL} /* LÂŤL‚ (ĂĽ */ }; void initspam(void) { annCharles@tom.com

1205Â?, 208Â?

Python ÆS)P


ĂŠ Python *Ă? Py_InitModule("spam", SpamMethods); } ¡Â‚F"ĂŻĂĄÂ˜Â‡module Âśi Šspam§¡ÂŒÂąĂ?Lspam.system(cmd) Â?ª§ ¤ Ăšos.systemaq óŠ" Ă„ k Š Ă› ˜ e Ăš ‡ § S § ˜ k Ăź ‡ Âź ĂŞ §initspam(...) §spam_system(...) §Â˜Â‡ Ă›CÞ§SpamMethords "initspam´ ÂŹĂ?ŠzŸê§ import žÿN ^§§ ´Â?˜ š¡ Ÿê"Âśi´init + module_name /ª§¡Â‚ module ‰spam"ÂŚÂƒ umain Ÿê"ÂŚ ĂŒÂ‡?Ă–´Ă? python )ºÏ§¡Â‚ spam ÂĽkĂľ ‡Ÿê"Py_InitModule Ă’´ZĂšÂ‡ÂŻÂœ "1˜‡Íê´"spam" §LÂŤmodule ϴ"1 ‡Íê´SpamMethords ´Â˜Â‡L‚§Ă? python §¡Â‚ spam kĂľ ‡Ÿ ĂŞ"SpamMethors ˜½Â‡´ Ă› ¡ CÞ§a.´PyMethodDef" PyMethordDef Âą ˜LÂŤL‚ (ĂĽ"z˜1ko‡iĂŁÂľ • 1 ˜ ‡ L ÂŤpython ÂĽ Âź ĂŞ Âś i § Ăš p ´ system§ 3python ÂĽ ÂŒ Âą Ă? Lspam.system 5N^ڇŸê" • 1 ‡iã´Â˜Â‡ŸêÂ? §spam_system§Ú‡Ÿê .˜½Â‡´ static PyObject * spam_system(PyObject * self, PyObject * args); Â? ĂšMETH_VARARGSÂƒĂŠA" • 1n‡iã´doc string§3python ÂĽÂŒÂąĂ?Lspam.system.__doc__ " •  Â˜ i ĂŁ ´ ˜ ‡ á(macro) § L ÂŤ Âź ĂŞ a . " lCŠ Ăł * : 5 w §Python ÂĽ Âź ĂŞ k Ăź ÂŤ § ˜ ÂŤ ´ ~ ^ ^tuple 5 D 4 ĂŤ ĂŞ § ˜ „ ´METH_VARARGSL§Â˜´^dictionary 5D4ꐤ ‰ keyword parameter§ ^METH_VARARGS|METH_KEYWORDSLÂŤ"Ú߇Macro Ă’ŠOĂŠAÚߍŸê"ߍ Â?ÂŞ3C Šó¼ÊA Ÿê .´Ă˜Â˜ " w w ¡ ‚ Ă˝ Z š Âź ĂŞspam_system§ ÂŚ ˆ ÂŁ Š L ÂŤPython ÂĽ Âź ĂŞ ˆ ÂŁ Š §â€œÂ˜ ƒ Ă‘ ´ ĂŠ –â€? Ăš ĂŠ { 3C Š Ăł ÂĽ L y / ÂŞ Ă’ ´PyObject* § ˜ ƒ Ă‘ ´PyObject*"XJц§@o3C Šó¼kŸê§ÂŒÂą^5 ÑÉ~§ÂˆÂŁÂŠĂ’´NULL " spam_system ĂŤĂŞk߇§w Œ‚ a.´PyObject*Ă’Â˜:Â?Ă˜Ă›% j" • self Â˜Â„Ă˜^§XJ´Ă˜Ă“Ÿê {§Œo´NULL§XJΫ˜‡class methord {§self LÂŤclass instance" • argsLÂŤD?5 Í꧴˜‡tuple §5Âżtuple 3C SĂœÂ?´PyObject* annCharles@tom.com

1206Â?, 208Â?

Python ÆS)P


§5.1 ^C? *Ă? ÂŹ PyArg_ParseTuple^5 ĂŤĂŞ"Ù¼args ´D?5 ĂŤĂŞ""s"L‚ª=† a .iĂŽG§sLÂŤstring a.§Â„kĂ™§a." ÂĄ Íê҇Ú"s"¤Â?½ a.ƒ¡A" Ăš"s" ƒ¡A a.´char**§´Â˜Â‡iĂŽÂ? Â? "Â?Ă’´`§Ă˜^¡Â‚gC5? S +n Ÿê§XJPythonÂĽXĂšŸêPyArg_ParseTuple ~ˆ£§@ocommandĂ’Â? •˜‡k iĂŽG"XJ´Â”}§@oĂ’ÂˆÂŁNULL" PyArg_ParseTuple ”} žÿ§ ÂŚÂŹgĂ„ ÑÉ~ §Ă˜^¡Â‚gC3? ÑÉ~ “è"ĂšÂ?wÑÉ~ś Ă??" eÂĄĂ’´N^system §Ú ĂšC Šó?§vkÂ&#x;oĂź "¡Â‚rsystem ÂˆÂŁÂŠ sts ŠÂ?¡Â‚Ÿê ÂˆÂŁÂŠ"Py_BuildValue()´^5MĂŻÂ˜Â‡python ʖ^ §ÂˆÂŁ ˜‡PyObject* §Œ 1Â˜Â‡ĂŤĂŞ^5Â?²Ê– a.""i"LÂŤinteger" ÂĄ ÍêÚÍ ĂŞa.ƒ˜—"Ă„KÂŹ ÑÉ~§ÂˆÂŁNULL" ¡uy*Ă?Python '^Python ?§I‡J þ§Ă’”? °Ă„§S‡'ĂŠĂ? A^§ SJ§Ă?Â?Ă˜ ‡ÊXĂšN^ )§Â„‡Ê܊XĂš SĂœk

)"*Ă?Python Â?´Â˜ §I‡ÊPython ¢yśk¤ )"Ă? §y3¡Â‚‡)¤¡Â‚ module "^C Š Ăł module ´kߍÂ?{\ Python ÂĽ"˜´r† ĂšPython “èÂ˜ĂĽ?Ăˆ" 3Unix² e§Ê{ߧÂ?‡3Modules/Setup.localÂĽ\ĂžÂ˜1§ spam spammodule.o , §rspammodule"c € Modules 8šeÂĄĂ’ÂŒÂą "­#?ĂˆPython "ڇÂ?{ kw ´Â„ ":§­#?ĂˆPython ÂŒvkÂ&#x;oĂ? " 1 ‡Â?{§rC §S?Ăˆ¤Â?Ă„ ĂŤ ÂĽ" ´k‡¯K§Ă˜Ă“² eĂŠĂ„ ĂŤ ÂĽ |ÂąÂ?ª´Ă˜Â˜ §OĂŠÂŒ"3Ă?§¡Â‚k˜‡distutils package ÂŒÂąÂ?¡ Â‚Â‰ĂšÂ‡ÂŻÂœ"? ˜‡setup.py ŠÂ‡§ŠÂ‡SNXe" $ls setup.py spammodule.c $cat setup.py from distutils.core import setup, Extension module1 = Extension(’spam’, sources = [’spammodule.c’]) setup (name = ’spam package’, version = ’1.0’, description = ’This is a spam package’, ext_modules = [module1]) äN Âżg§ÂŒ¹Í distulis $python setup.py build running build running build_ext annCharles@tom.com

ĂƒĂž"

#?Ăˆ

1207Â?, 208Â?

Python ÆS)P


ĂŠ Python *Ă? building ’spam’ extension creating build creating build/temp.linux-i686-2.2 gcc -DNDEBUG -g -O3 -Wall -Wstrict-prototypes -fPIC \ -I/usr/include/python2.2 -c spammodule.c \ -o build/temp.linux-i686-2.2/spammodule.o creating build/lib.linux-i686-2.2 gcc -shared build/temp.linux-i686-2.2/spammodule.o \ -o build/lib.linux-i686-2.2/spam.so $ $ls #Ăľ ˜‡build f8š build setup.py spammodule.c $cp build/lib.linux-i686-2.2/spam.so . #€ c8š $python #$1python )ºÏ Python 2.2 (#1, Apr 12 2002, 15:29:57) [GCC 2.96 20000731 (Red Hat Linux 7.2 2.96-109)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import spam #Ăš\¡Â‚ module >>> print spam.system.__doc__ # w DOC string Execute a shell command. >>> print spam.system("echo ’hello’") #ww¤þ Ă­Âş hello #ok, ~Ă‘Ă‘ 0 # spam.system ÂˆÂŁÂŠ >>>

annCharles@tom.com

1208Â?, 208Â?

Python ÆS)P


Turn static files into dynamic content formats.

Create a flipbook
Issuu converts static files into: digital portfolios, online yearbooks, online catalogs, digital photo albums and more. Sign up and create your flipbook.