Top Banner
Python ˘S)P X [email protected] or [email protected] 2003c0826F
160

强烈推荐Ann77+python

Sep 03, 2014

Download

Technology

whitecrow_

 
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: 强烈推荐Ann77+python

Python ÆS)P

�X�

[email protected] or [email protected]

2003c08�26F

Page 2: 强烈推荐Ann77+python

[email protected] 12�,�152� Python ÆS)P

Page 3: 强烈推荐Ann77+python

8 ¹

8 ¹

111���ÙÙÙ Python000��� 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

[email protected] 1i�,�152� Python ÆS)P

Page 4: 强烈推荐Ann77+python

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 Щz¼ê . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 46

§1.13.2 �{(method) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47

§1.13.3 á5(property) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48

§1.13.4 U«(inherit) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 49

§1.13.5 ­1(overload) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 49

§1.13.6 class �attribute . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 49

§1.13.7 Abstrace Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50

§1.13.8 Python�¡�é�?§ . . . . . . . . . . . . . . . . . . . . . . . . . . 50

§1.13.9 Python ¥class AÏ�methord . . . . . . . . . . . . . . . . . . . . . 50

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

§1.14.1 �o´É~?n§��o�kÉ~?n . . . . . . . . . . . . . . . . . 57

§1.14.2 Ó¼exception(É~) . . . . . . . . . . . . . . . . . . . . . . . . . . . 59

§1.14.3 �Ñexception . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 63

111���ÙÙÙ mmmuuuPython ¦¦¦^���óóóäää 66

§2.1 ¦^Emacs ?6Python §S . . . . . . . . . . . . . . . . . . . . . . . . . . . 66

[email protected] 1ii�,�152� Python ÆS)P

Page 5: 强烈推荐Ann77+python

8 ¹

§2.1.1 SCpython mode . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 66

§2.1.2 python mode �Ä�A5 . . . . . . . . . . . . . . . . . . . . . . . . . 67

§2.1.3 ~^õUÞ~ . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 67

§2.2 Ù¦?6ì . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 69

§2.3 NÁ§S . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 70

§2.3.1 ¦^DDD Úpydb NÁpython §S . . . . . . . . . . . . . . . . . . . . 70

111nnnÙÙÙ Python ���~~~^���¬¬¬ 71

§3.1 S��¬ . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 71

§3.1.1 ~^¼ê . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 71

§3.1.2 a.=�¼ê . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73

§3.1.3 ^u�1§S�S�¼ê . . . . . . . . . . . . . . . . . . . . . . . . . 75

§3.2 Úö�XÚ�'�N^ . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 78

§3.2.1 �m©� . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81

§3.2.2 Ö�©� . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81

§3.2.3 '4©� . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 82

§3.3 regular expression . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 82

§3.3.1 {ü�regexp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 83

§3.3.2 iÎ8Ü . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 83

§3.3.3 ­E . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 85

§3.3.4 ¦^�©iÎG . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 85

§3.3.5 ¦^re �¬ . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 85

§3.3.6 p?regexp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 87

§3.3.7 ©|(Group) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 88

§3.3.8 Compile Flag . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 90

§3.4 ^struct�¬?n�?�êâ . . . . . . . . . . . . . . . . . . . . . . . . . . . 91

§3.5 ^Cmd �¬?�{ü�·-1�� . . . . . . . . . . . . . . . . . . . . . . . . 93

§3.5.1 {ü�~f . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 94

§3.5.2 ½Â%@·- . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 95

§3.5.3 ?nEOF . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 95

§3.5.4 ?n�·- . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 96

§3.5.5 ·-1gÄÖà . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 96

[email protected] 1iii�,�152� Python ÆS)P

Page 6: 强烈推荐Ann77+python

8 ¹

§3.5.6 UCIOÑ\ÑÑ . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 96

§3.5.7 UCJ«Î . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 97

§3.5.8 Jø3��ÏõU . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 97

§3.5.9 $1Shell �õU . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 98

§3.5.10 getattr õU�¦^ . . . . . . . . . . . . . . . . . . . . . . . . . . . . 98

§3.6 ?n·-1À� . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 99

§3.6.1 ��{ü�~f . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 99

§3.6.2 �këê�·-1À� . . . . . . . . . . . . . . . . . . . . . . . . . . . 100

§3.6.3 optparser �¬ . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 101

§3.7 'u�m��¬ . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 109

111oooÙÙÙ Tkinter ???§§§ 111

§4.1 Tkinter0� . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 111

§4.1.1 �o´Tkinter . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 111

§4.2 Hello Tkinter §S . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 112

§4.2.1 {ü�~f . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 112

§4.2.2 ,��{ü§S . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 114

§4.3 Widget ��� . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 115

§4.4 Geometry Manager(AÛ+nì) . . . . . . . . . . . . . . . . . . . . . . . . . 116

§4.4.1 Pack +nì . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 117

§4.4.2 Grid +nì . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 120

§4.5 Widget ��ª . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 122

§4.5.1 ôÚ . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 122

§4.5.2 iN . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 123

§4.5.3 ©i�ªz . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 126

§4.5.4 >µ . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 126

§4.5.5 àI . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 128

§4.6 ¯�Ú¯���½ . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 130

§4.6.1 ��{ü�~f . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 130

§4.6.2 ¯�?n¼ê . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 132

§4.6.3 ¯���g . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 132

§4.6.4 Ó��¯��õ�?n¼ê . . . . . . . . . . . . . . . . . . . . . . . . 135

[email protected] 1iv�,�152� Python ÆS)P

Page 7: 强烈推荐Ann77+python

8 ¹

§4.6.5 ÚWM �'�¯��½ . . . . . . . . . . . . . . . . . . . . . . . . . . 136

§4.7 ~^�A^§S¦^�Widget . . . . . . . . . . . . . . . . . . . . . . . . . . . 137

§4.7.1 Ä�I� . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 137

§4.7.2 èü . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 137

§4.7.3 óä9 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 141

§4.7.4 G�9 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 141

§4.7.5 IOé{µ . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 143

111ÊÊÊÙÙÙ Python���***ÐÐÐ 149

§5.1 ^C?�*Ð�¬ . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 149

[email protected] 1v�,�152� Python ÆS)P

Page 8: 强烈推荐Ann77+python

L �

L �

1.5-1 iÎG¥�=¿iÎ . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14

1.5-2 iÎG=��Ù¦a. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14

1.5-3 �äiÎG´Äáu,«aO�¼ê . . . . . . . . . . . . . . . . . . . . . . 16

3.1-1 Python �­^S�¼ê . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 72

3.1-2 a.=�¼ê . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 74

3.2-3 XÚN^Þ~ . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 78

3.4-4 struct �¬¥��ª½Â . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 92

3.4-5 i!^S½Â . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 93

3.5-6 ·-1?6�¯$� . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 94

3.7-7 L«�m� . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 110

4.5-1 tkFont |±�option . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 125

4.6-2 ¯�£ãÞ~ . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 133

4.6-3 £ã¯��ëê . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 133

[email protected] 1vi�,�152� Python ÆS)P

Page 9: 强烈推荐Ann77+python

111���ÙÙÙ

Python000���

python´�«)º5�¡�é���ó"pythonk±eA:"

)))ººº... �Ý ú§mu±Ïá§NÁN´§g·*Ð5"dukeval�õU§?��§S�±3$1�UYmu"ù´éõ)º.�ó��5"XVB kScript Engi-neer§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.��"

���iii\\\ Python�)ºìÚ��±éN´�i\�^rgC�C½öC++�ó§S�8¥§¦\�§S�±|±��?§§*ÐõU"y3ÒkPython��¬�±*ÐVIMÚEmacs�õU"

���SSSØØØ Python�Ø%)ºì´é��"

ÄÄÄ���aaa... ØI�¯k(²(declare)Cþ�a.§��¦^CþÒ�éõÙ¦)º.�óVB§VB Script§JScript§PERL��"

rrraaa... ¦+CþØ^(²(declare)a.§�´��Cþk�§@où��´k��a.�"ØUòstringa.�Cþ��D����integera.�Cþ§ ´I�a.=�"ùÚVB§VBScript§JScript§PERLØ��§ÚJava �"

[email protected] 11�,�152� Python ÆS)P

Page 10: 强烈推荐Ann77+python

� 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 40 Sep 12 13:34 test.py

$chmod +x test.py

$ls -l test.py

[email protected] 12�,�152� Python ÆS)P

Page 11: 强烈推荐Ann77+python

§1.2 ����é�

-rwxr-xr-x 1 chunywan mnw 40 Sep 12 13:34 test.py

$./test.py

Hello World

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+ \{ 1+1 2− ~{ 1-1 0∗ ¦{ 2*10 20/ Ø{ 10/3 3% � 10/3 1∗∗ � 2**4 16

divmod Ø{ divmod(10§3) (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éõ§�)

[email protected] 13�,�152� Python ÆS)P

Page 12: 强烈推荐Ann77+python

� Python0�

None,0,0.0,"" (�iÎG),[](�list),()(�tuple),{}(�dictionary)

Python¥k±eÜ6$�Î"

and Ü6�or Ü6½not Ü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��ª:

[email protected] 14�,�152� Python ÆS)P

Page 13: 强烈推荐Ann77+python

§1.3 Ä�a.

<cond> and <expr_true> or <expr_false>

¦k��ék^��´: XJcond ¤á§@o�£expr_true§ÄK�£expr_false"¦vk���o5K§�´l��m�g"4·�5u��e��o:

cond expr_true expr_false o�(Jý ý ?Û(ØO�) expr_true

b ?Û(ØO�) ý expr_false

b ?Û(ØO�) b expr_false

ý b b expr_false

ý b ý 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§¯��”§

[email protected] 15�,�152� Python ÆS)P

Administrator
Highlight
Page 14: 强烈推荐Ann77+python

� Python0�

�´·�ج`§“r§?ê�”§½ö“r§? ”§Ø´Ï�@o`Ò´��§´Ï�ØÜS."@Ò¬¯§��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 1����... ...-2 �ê1����-1 ������0 1����1 1����... ...

len-1 ������

>>> a=[0,1,2,3,4,5,6]

[email protected] 16�,�152� Python ÆS)P

Page 15: 强烈推荐Ann77+python

§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�¡0�"a[-8] Úa[9] ѬÚå�."

>>> a[-8]

Traceback (most recent call last):

File "<stdin>", line 1, in ?

IndexError: list index out of range

>>> a[7]

Traceback (most recent call last):

File "<stdin>", line 1, in ?

IndexError: list index out of range

§1.4.3 flist�J�

�ÏLeI�½��§^uJ�Ñ��list��Ü©"eIL² �§��å© �§��(å �§¥m^kÒ©�"XJØ�½å© �§å© �´0 §XJØ�½(å �§(å �´−1"flist L«�)å© �?���§���(å �§�´Ø�)(å ����"

KeI��±ë�½Âå© �§½ö(å �"

>>> a[1:4]

[email protected] 17�,�152� Python ÆS)P

Administrator
Highlight
Page 16: 强烈推荐Ann77+python

� Python0�

[1, 2, 3]

>>> a[:]

[0, 1, 2, 3, 4, 5, 6]

>>> a[1:]

[1, 2, 3, 4, 5, 6]

>>> a[:3]

[0, 1, 2]

>>> a[:]

[0, 1, 2, 3, 4, 5, 6]

>>> a[1:-1]

[1, 2, 3, 4, 5]

���flist ´�5list �����§��B�§UCflist جUC�5�list"

§1.4.4 ?nlist��{

• L.append(var) §J\��"

>>> a=[0,1,2,3,4,5]

>>> a.append(6)

>>> a

[0, 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])

[email protected] 18�,�152� Python ÆS)P

Page 17: 强烈推荐Ann77+python

§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\"

>>> a=[1,2]

>>> a.insert(0,1)

>>> a

[1, 1, 2]

>>> a.insert(100,100)

>>> a

[1, 1, 2, 100]

>>> a.insert(2,3)

>>> a

[1, 1, 3, 2, 100]

• L.pop() �£������§¿�íØ������"L.pop(index) �£index?���§¿�íØT��"

>>> a=[0,1,2,3,]

>>> a.pop()

3

>>> a.pop(0)

0

>>> a

[1, 2]

>>>

• L.remove(var) é�var§¿�íØ�§eç�ÑÉ~"

[email protected] 19�,�152� Python ÆS)P

Administrator
Comment on Text
这里的index<0满足条件为:L为空,ex:L=[],或者L为负下标LIST, ex:L=[-2,-4,-6]。 在正整数下标的LIST中插入index<0,则会从max(len(L))往min(len(L))方向插入。
Page 18: 强烈推荐Ann77+python

� 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"

>>> a=[1,2,3,4,5]

>>> a.reverse()

>>> a

[5, 4, 3, 2, 1]

• L.sort() §òaüS§a¥��ea.ØÓ§(JgCw�wj"��جùo�"Q,\ÑØ(½list¥����a.´Ä��§\��üS§@o\Ï�´�o(J?

>>> a.sort()

>>> a

[1, 2, 3, 4, 5]

>>> a=[1,"abc",2,"xxx"]

>>> a.sort()

>>> a

[1, 2, ’abc’, ’xxx’]

L.sort(func) §ò^func��'�¼ê§òüS"func(x,y)§�£−1§0§1©OL«�u§�u§�u"

§1.4.5 ^list �[Ù¦~^êâ(�

^list�[æÒstack

>>> a=[]

>>> a.append(0) #ØÒ>>> a.append(1)

>>> a.append(2)

>>> a

[0, 1, 2]

>>> a.pop() #ÑÒ2

[email protected] 110�,�152� Python ÆS)P

Page 19: 强烈推荐Ann77+python

§1.4 �L(list)

>>> a.pop()

1

>>> a.pop()

0

>>>

^list�[è�queue

>>> a.insert(-1,0) #\è>>> a.insert(-1,1)

>>> a.insert(-1,2)

>>> a

[2, 1, 0]

>>> a.pop() #Ñè0

>>> a.pop()

1

>>> a.pop()

2

>>> a

[]

½ö

>>> a.append(0)

>>> a.append(1)

>>> a.append(2)

>>> a.append(3)

>>> a

[0, 1, 2, 3]

>>> a.pop(0)

0

>>> a.pop(0)

1

>>> a.pop(0)

2

>>> a.pop(0)

3

[email protected] 111�,�152� Python ÆS)P

Page 20: 强烈推荐Ann77+python

� 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 ’, ’ AAA ’]

#��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]

LÈ(filter)§ÚN�(mapping)Ú���"

¦+ù�^{é{ü§�´%�©k^§§SC�{'§�Ö5r"kéõ�ÿ§·�¦^Ì��é§==�é{ü�¯�§�´Ì��é��´éØÐÖ�§Ï�Ì��éØÎ

[email protected] 112�,�152� Python ÆS)P

Administrator
Sticky Note
左边例子中 if 后面的属性使用,前提是 L 列表中元素的类型都允许使用该定义属性(比如都是字符符,所以允许使用 isalpha() 属性,左边的例子就是将L列表中的元素全部定义为字符串型)
Page 21: 强烈推荐Ann77+python

§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.

"""

[email protected] 113�,�152� Python ÆS)P

Administrator
Highlight
Page 22: 强烈推荐Ann77+python

� Python0�

�è L«�iÎ ¿Â �5\newline à �Ñ ^uë�õ�á

1§�¤���1

\\ \ ��m\’ ’ üÚÒ\" " VÚÒ\a 0x07 �$ ASCII ��iÎ\b 0x08 ò� ASCII ��iÎ\f 0x0c Formfeed (FF) ASCII ��iÎ\n 0x0a �1 ASCII ��iÎ\N{name} Unicode iÎ ��éuUnicode\r 0x0d £� ASCII ��iÎ\t 0x09 Y²�LÎ\v 0x0b R��LÎ\u{xxxx} Unicode?è ��éuUnicode\ooo 0xooo ooo L«�l?�iÎ\xhh 0xhh hh L«��8?�iÎ

L 1.5-1: iÎG¥�=¿iÎ

¼ê¶¡ õU ~f (Jfloat(str) C¤2:ê float("1e-1") 0.1int(str) C¤�. int("12") 12int(str,base) C¤base?��ê int("11",2) 2long(str) C¤��. int("12") 12long(str,base) C¤base?���ê int("11",2) 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��

[email protected] 114�,�152� Python ÆS)P

Page 23: 强烈推荐Ann77+python

§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�Ó��ª��fG"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"

[email protected] 115�,�152� Python ÆS)P

Page 24: 强烈推荐Ann77+python

� 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() ¤kiÎÑ´êi0123456789 ½öi1A-Z§a-zs.isalpha() ¤kiÎÑ´i1a-z ½öA-Zs.isdigit() ¤kiÎÑ´êi0123456789s.islower() ¤kiÎÑ´��i1a-zs.isupper() ¤kiÎÑ´��i1A-Zs.istitle() ¤kücÑ´Äi1��§��titles.isspace() ¤kiÎÑ´�xiÎ\n,\t,\r,’ ’

L 1.5-3: �äiÎG´Äáu,«aO�¼ê

[email protected] 116�,�152� Python ÆS)P

Administrator
Highlight
Page 25: 强烈推荐Ann77+python

§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

[email protected] 117�,�152� Python ÆS)P

Page 26: 强烈推荐Ann77+python

� Python0�

�ªziÎG

Ä�^{´ s % <tuple> §tuple L«��ëê�L§aquC�ó¥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>|

wXé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’

[email protected] 118�,�152� Python ÆS)P

Page 27: 强烈推荐Ann77+python

§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�Ð?´§Jp§S��Ö5§%dÚ%(height)'

�§�ö��Ö5�Ð" �§Ó����CþÑyüg±þ§3tuple¥Ò��üg§ ��5¿tuple¥���^SÚ�êØ��§^mapping key��ªÒÐõ"

[email protected] 119�,�152� Python ÆS)P

Page 28: 强烈推荐Ann77+python

� 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()�£globalname 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Ò3c¡\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¡\-§

[email protected] 120�,�152� Python ÆS)P

Page 29: 强烈推荐Ann77+python

§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�o�Ø�"

>>> "Hello World".center(1)

’Hello World’

>>> "Hello World".center(16)

’ Hello World ’

• �K�xiÎs.lstrip() �K�>��xiÎs.rstrip() �Km>��xiÎs.lstrip() �Kü>��xiÎ

>>> "\t a \t".lstrip()

’a ’

>>> "\t a \t".rstrip()

[email protected] 121�,�152� Python ÆS)P

Page 30: 强烈推荐Ann77+python

� Python0�

’ a’

>>> "\t a \t".strip()

’a’

#��python 2.2.3¥O\���Àëêchars§L«íØÑy3chars¥�iÎ"Î��s.strip ��us.strip("\t \n\r")"

iÎG�Ü¿(join)Ú©)(split)

s.join(words)§words´���¹kiÎ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�"

>>> a,b=(1,2)

>>> print a,b

1 2

>>> t=(1,2)

>>> a,b=t

>>> print a,b

1 2

[email protected] 122�,�152� Python ÆS)P

Page 31: 强烈推荐Ann77+python

§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�oÑ�±"dictionary¥vk­E�key"dictionary¥�z����´��tuple§tuple¥kü���§ù�tuple�pair§pair¥c¡�´key§�¡�value"�±^D[key] ��ª��value"

1½ö?ÛÓ�¹k hash Ú cmp �{�é�

[email protected] 123�,�152� Python ÆS)P

Page 32: 强烈推荐Ann77+python

� 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

{}

[email protected] 124�,�152� Python ÆS)P

Page 33: 强烈推荐Ann77+python

§1.8 i;(dictionary)

����dictionary

D.copy()

����dictionary �����

>>> a

{’four’: 4, ’three’: 3, ’two’: 2, ’one’: 1}

>>> b=a.copy()

>>> b

{’four’: 4, ’one’: 1, ’three’: 3, ’two’: 2}

>>> b["four"]=5

>>> b

{’four’: 5, ’one’: 1, ’three’: 3, ’two’: 2}

>>> a

{’four’: 4, ’three’: 3, ’two’: 2, ’one’: 1}

>>> c=a

>>> c["four"]=5

>>> a

{’four’: 5, ’three’: 3, ’two’: 2, ’one’: 1}

>>> c

{’four’: 5, ’three’: 3, ’two’: 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)"

[email protected] 125�,�152� Python ÆS)P

Page 34: 强烈推荐Ann77+python

� 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]

[email protected] 126�,�152� Python ÆS)P

Page 35: 强烈推荐Ann77+python

§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

�{

[email protected] 127�,�152� Python ÆS)P

Page 36: 强烈推荐Ann77+python

� 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 �é¬�Ð

[email protected] 128�,�152� Python ÆS)P

Page 37: 强烈推荐Ann77+python

§1.9 §S6§

... print "x is positive"

... elif x==0:

... print "x is zero"

... elif x < 0:

... print "x is negative"

... else:

... print "x 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��"

[email protected] 129�,�152� Python ÆS)P

Page 38: 强烈推荐Ann77+python

� 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¥

>>> a

[1, 2, 3, 4]

>>> for x in a:

... if x==100: break

... else:

... print "100 not found"

...

100 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"

>>> a=[1,2,3,4]

>>> for x in a:

... x=x+1

...

>>> x

5

>>> a

[1, 2, 3, 4]

3ÄKÌ�Ò��¿Â

[email protected] 130�,�152� Python ÆS)P

Page 39: 强烈推荐Ann77+python

§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"

>>> range(10)

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

>>> range(1,10)

[1, 2, 3, 4, 5, 6, 7, 8, 9]

>>> range(1,10,2)

[1, 3, 5, 7, 9]

>>> range(1,10,-1)

[]

e�U�)Ã��ê§@o´�list§Ø¬kkÌ�"|^range()¼ê?Ulist

>>> a

[1, 2, 3, 4]

>>> for x in range(len(a)):

... a[x]=a[x]+2

...

>>> a

[3, 4, 5, 6]

>>>

while��{"

while <expr1>:

<block>

else:

<else-block>

[email protected] 131�,�152� Python ÆS)P

Page 40: 强烈推荐Ann77+python

� Python0�

ù�Ì��¿g´§��expr1´ý§@oÒ���1block¥��é"XJvbreakaÑÌ�§�Ò´`§3Ì�(å��ÿexpr1´b§@o�1else-block¥

��é"

>>> i=0

>>> while i < 3:

... print i ; i=i+1

...

0

1

2

>>> while i < 3:

... print i; i = i +1

... else:

... print i , "is 3"

...

0

1

2

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�Ó� ?"

[email protected] 132�,�152� Python ÆS)P

Page 41: 强烈推荐Ann77+python

§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

...

[email protected] 133�,�152� Python ÆS)P

Page 42: 强烈推荐Ann77+python

� 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’>

[email protected] 134�,�152� Python ÆS)P

Page 43: 强烈推荐Ann77+python

§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

Ó þ � « Å � a q § � Ø L**keyword´ ^**L « � É ? ¿ �ê � k ¶ i � ë ê D 4 § � ´ 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�?¿ëê"

[email protected] 135�,�152� Python ÆS)P

Page 44: 强烈推荐Ann77+python

� 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�é´��é§�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´ �

[email protected] 136�,�152� Python ÆS)P

Page 45: 强烈推荐Ann77+python

§1.10 ¼ê

«functional programming language"ØÙGfunctional programming �<§�±@�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

>>> def incfun(a):

... return lambda x: x+a

...

>>> incfun(2)(12)

14

>>> incfun(2)(13)

15

>>> incfun(4)(13)

17

>>>

§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"

>>> a=1

>>> def testfun():

... a=2

... print a

...

>>> testfun()

2

>>> a

1

3¼êtestfun()¥a´3local name space¥§?UaجUCglobal name space¥�a

�´§^global�é�±?U��Cþ�¤3�name space"

[email protected] 137�,�152� Python ÆS)P

Page 46: 强烈推荐Ann77+python

� Python0�

>>> a=1

>>> 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]

[email protected] 138�,�152� Python ÆS)P

Page 47: 强烈推荐Ann77+python

§1.11 �¬(module)Ú�(package)

>>> change(x,y)

>>> 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§�´UCname 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 direc-tory)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

>>>

[email protected] 139�,�152� Python ÆS)P

Page 48: 强烈推荐Ann77+python

� Python0�

�±�¯testmodule¥�attribute

>>> 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 �Vg5)ºÒ�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

[email protected] 140�,�152� Python ÆS)P

Page 49: 强烈推荐Ann77+python

§1.11 �¬(module)Ú�(package)

<function sayHello at 0x81631a4>

>>> 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§¿vk�import ?5§�Ò´`§�cname space ¥vktestmodule ù���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’]

[email protected] 141�,�152� Python ÆS)P

Page 50: 强烈推荐Ann77+python

� Python0�

l�é^Sþw§·��±��XJ\3�c8¹ïá��ÚIO¥¥�k�IOmodulek�Ó�¶i@o¬^\�module �OXÚmodule§¬�)#¶Ù©�¯K§¤±·��5¿§gC�module ¶iØ�ÚXÚ�module¶i�Ó"

§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�ߧVgÚ���ó"

�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 (S3�·¶�m)global name space (�Û·¶�m)§local name space(ÛÜ·¶�m)"3ØÓname space¥�name ´�:'X�vk�"$�i¡þ�Óname§��¦�3ØÓ�name space

[email protected] 142�,�152� Python ÆS)P

Page 51: 强烈推荐Ann77+python

§1.12 name space(·¶�m)

¥§@o¦�ÒÎÃ'é"UClocal name space ¥�name�bind 'X§Ø¬K��globalname space ¥�Ó�name"

z�object ÑkgC�name space"�±ÏLobject.name ��ª�¯object �namespace ¥�name"z�object �name space ´Õá�"“Õá�”�¿g´`§��object�name space ¥���name§ÚÙ§name space ¥�name ´�:'X�vk�§$�ü�i¡þwå5���name§�´ÎØ�Z�"Ò�“�f” ù�object§3¦�namespace ¥k��“ôÚ”§ù���name §L«���f�ôÚ§ “�f”ù�object §3¦�name space ¥�k��“ôÚ”§ù�name L«�f�ôÚ§¦Ú�f�:'X�vk§¦+¦�Ñ�“ôÚ”"

·@�¦+name space ´��p?Vg§�´¦´é�ß�Vg§��N´n)�Vg"{ü�Vg�¡ÛõX��¯"name space ´ù�)P¥`��õ§�Û����Vg"·@�§¦´python �Ø%Vg§Ò�file ù�Vgunix ¥��"

z � �object § Xmodule§class§function§ � �instance § Ñ k g C �namespace"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__§^5L«module �©�¶¡"¤±3�import ��ÿ§ÿÁ�èÒ�Ø�3��§Ï�__name__§[�ج´“__main__”"�´XJ^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()

[email protected] 143�,�152� Python ÆS)P

Page 52: 强烈推荐Ann77+python

� Python0�

... print globals()

...

>>>

>>> testfun()

{}

{’__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 5L«§dictionary ´��(key§name)ù��pair �8ܧkey´name§value´name ¤��object"

�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�5K^scope�Vg5)ºÒ´: 3?Û�è�1��ÿ§Ñ��kn�scope§��´local name space |¤�scope"��´�cmodule �global name space|¤�scope§�kbuildin name space |¤�scope"lS��g�é��unqualifiedname"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

[email protected] 144�,�152� Python ÆS)P

Page 53: 强烈推荐Ann77+python

§1.12 name space(·¶�m)

>>> saidHello()

Hello

�±w�sayHello§saidHello¦�ØL´ü�¶i§¦���´Ó��object"Ò���<kü�¶i��"a=[1,2]ù��駬3�SÜ�name space þMï��nameÚ[1,2]ù�object �½(bind)"ù«D��éج��êâ§�´3namespace¥Mï��#�name§����object"ùé­�"Ò�java ¥¤k�CþÑ´Ú^(reference)��§�ÚC ¥pointer(��)kaq"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 ¥�-ãÂkaq"ÚCÚC++¥�U���Eâé�"

¢Spython ¥Ò´¦^�U���Eâ§z�name ÑÚ��object����'é§z��objectÑk��referece counter P4kõ��name Úù�object bind"zgbind§reference count Ñ\1§zgíØbind 'X§Ñ~�1§�kreference counter C¤0��ÿâý�íØé�"

python ´�«ra.§Ä�a.��ó"

ra.´�§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ØÃ\�.��o"

z�é�ÑkgCÕá�name space"z«a.kgCÕá�ö��{"é��namespace ¥name ¬Ú,�ö��{�éA"Cþ==´é��¶i"

[email protected] 145�,�152� Python ÆS)P

Page 54: 强烈推荐Ann77+python

� Python0�

Ä�a.´�z�CþÑØ^(²§�±��?Ûa.�é�"½ö�Cþ(variable)�¶i(name)��Ü·"Cþ�´��é��¶i§z�Cþ3,�������é�§�´��é��±Ó�kõ�Cþ��¦§Ò�¼ê§module §class Ñ�±kalias (O¶)"Cþ�)�Ï�Úé��)�Ï´Ø���"�vk?ÛCþ����é���ÿ§ù�é�â�ý�íØ" ��Cþ��±��UC¦��½'X§=��Ù¦é�"

ù«L��ªÚ·��y¢­.´��"

§1.13 a��CPython�Ø%"¡�é�(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)"

���{ü�a

>>> class SimplestClass:

... pass

...

¦�o�vZ§�´·��±gÍ�`§·k·�1��class"

§1.13.1 Щz¼ê

>>> class SampleClass:

... def __init__(self):

... print "OK, I was born."

...

>>> a=SampleClass()

OK, I was born.

>>> AClass = SampleClass

>>> b=AClass()

OK, I was born.

>>>

3PythonvkC++¥��E¼ê§ÚÛ�¼ê"�´kЩz¼ê§���objectMï�±�§¬gÄN^__init__"

[email protected] 146�,�152� Python ÆS)P

Page 55: 强烈推荐Ann77+python

§1.13 a

class Ú¼ê(function)��§�´��é�§�±D��ÊÏCþ§@où�CþÒC¤ù�a"ù«Å�aquC++ ¥�templateÅ�§�Ò´`§�±r��class��ëêD4���¼ê"�´Útemplate �Ø����"

~f¥§AClass = SampleClass Ò�function alias ��§ïá��class alias"

�±`class '�iMá,��Õá�name space §ù�n)§�¡�ÀÜÑ´g, ,�¯�"�¡0��ØL´éname space �Vg�?�Ú)º"¬²x��o¤k�¤CþÚ¤¼êÑ´J¼ê(virtual function)"

z�instance(¢~) Ñ´^¼êN^��ª�£�obj=ClassName()

z�objkgCÕá�name space"

§1.13.2 �{(method)

3class SܽÂ�¼êÑ´methord"�)__init__"z�methord��k��ëê§self§aquC++§Java¥�this"

ùpk�5K§XJla�SÜN^methord§@o�½��)self��1��ëê§XJ´N^é��methord§@o��N^§ÒÐ����selfëê��"

� ± n ) �: z � �class �methord Ñ � � k � � ë ê " eobj ´classA � � �instance§sayHello(self) ´class A � � �methord � { § @oobj.sayHello()ÚA.sayHello(obj)´���"

^name space �Vg5n)Ò��Ù§class Jø��ïá��Õáname space �Å�§z��instance ÑkgCÕá�name space"

3class�methord¥§self3methord�local name space¥§��class�instance"

� obj=A_Class() ��ÿ§Mï��instance §ù�instance kgCÕá�namespace §ù�name space ´A_Class�name space �����"

5¿§·`�´“��”§class�instance�name spaceÚclass�name space´��Õá�"

>>> class A:

... def sayHello(self):

... print "hello"

...

>>> obj=A()

>>> obj.sayHello()

hello

>>> A.sayHello(obj)

hello

self �L��instance ��"

[email protected] 147�,�152� Python ÆS)P

Page 56: 强烈推荐Ann77+python

� Python0�

§1.13.3 á5(property)

­E�`§class Ò´ïá��Õá�name space "?ÛSÜ�CþÑ´class �á5"á5´�±��ïá§��íØ�"XJobj vka �á5§@o?Û/�Ñ�±^obj.a =1 Mï��#�á5"ÃØ3class �methord ¥^self.a=1��ª�´3¡^obj.a=1��ª§Ñ�±Mï��#�á5"Ï�z�instance kgCÕá�namespace§�±g,�n)�§=¦Ó��class �ü�ØÓ�instance ��±kØÓ�á5"�±^del íØ��instance �á5"

>>> class A:

... name="abc"

...

>>> obj1=A()

>>> obj2=A()

>>> obj1.name="xyz" #UC obj1 Ñ name

>>> obj2.name #جK�obj2

’abc’

>>> obj1.name #Ï�¦�� name space

’xyz’ #´Õá�.

>>> class B:

... def __init__(self):

... self.a=1

...

>>> obj1=B()

>>> obj2=B()

>>> obj1.a #obj1 Ú obj2 Ñk1 #á5 a

>>> obj2.a

1

>>> del obj2.a #íØ obj2 �á5 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

[email protected] 148�,�152� Python ÆS)P

Page 57: 强烈推荐Ann77+python

§1.13 a

§1.13.4 U«(inherit)

U«��{�ª´

class <name>(superclass1,superclass2,...):

�±kõ�Ia"^name space �Vgn)Ò´r¤ksuperclass ¥�name spaceÜ¿§¿�O\g�½Â�#�name �name space ¥§l )¤��#�namespace"­E�`§class A�Ò´��MïÕáname space �Å�"�,��±^superclass.methord(self,...) ��{5�¯Ia��{"�\a�name space {ü�r�"

§1.13.5 ­1(overload)

A�Ø^�C++ ¥@�AO�)º�o´­1"Ï�class �±ïá��Õá�name space §z��instance ÑkgCÕáname space"class ¥ïá�#�name§XJÚ?ÛIaname space ¥���ӧѬ­#CX�5�bind 'X"�,��±^superclass.methord(childInstance)��ª�¯Ia��{"2gw�name space {ü�r�"

§1.13.6 class �attribute

�N\^LC++½öJava¥·�¤Cþ§Ò´Ó��class �ØÓinstance ��Ó��Cþ"python �kù«Å�§�´§Ø´Ú?�#�â�§�´^name space �Å�§¢y·���z��instance kÕá�name space§ class ���´��object §�k��Õáname space "z�instance �name space ¥Ñk��__class__�name §^5��MïTinstance �class é�"__class__dpython gÄMï§obj.__class__ ��obj�class"ù�ÒØJn)e¡�§S"

>>> class A:

... count = 0

... def __init__(self):

... self.__class__.count= self.__class__.count + 1

... #5¿Ø´self.count

>>> 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

[email protected] 149�,�152� Python ÆS)P

Page 58: 强烈推荐Ann77+python

� Python0�

>>> 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"Ó��÷vabstract class ��¦"ÐÆ¡�é�?§§ú�ù´Ã���è§�o�vkZ§ÆL��§uyù´¡�é��Ø%g���§©l��Ú¢y"

§1.13.8 Python�¡�é�?§

OO (¡�é�) ´�«?§g�§Ø´?§�ó§$�^®?�ó���±¡�é�§�,vk<¬@oZk�ó�OO JøéõB|§éN´¢yµC§U«§­1§õ�"Python§java§C++§SmallTalk ��"Python �¢yÅ�´�©{ü�§namespace"ù«�ª´{ü r��§�´�´N´�ÑéD��è§Ù§�ó���§X�{�Ø\�éD��è"�5�Þéõ~f§�´·ú�ù�)P´^5£ãPyton�ó���§ù�)PØU¦\¤�?§pç�UÙG���ó§Ò�Ƭ`{§�´Ø�½Ñ¬üù§ �X�{�Ø\�`l�§�ó�r�§�N´Ø�¤�§��§XJéÐ�ݺ�«?§g�(Ø´?§�ó)§^�o�óÑ�±ù�é�Ù§é²x§é¤�"

§1.13.9 Python ¥class AÏ�methord

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 Úù�objectkbind 'X��ÿ§¬N^¦"

[email protected] 150�,�152� Python ÆS)P

Page 59: 强烈推荐Ann77+python

§1.13 a

• __repr__(self) ¦^repr() ¼êN^��ÿ§�£Úeval() oN�é�iÎGL�ª§^u­ïé�"

• __str__(self) �B�£��iÎG£ãé���"e¡�~f`²__repr__

Ú__str__ �ØÓ"

>>> class A:

... def __repr__(self):

... return "A()"

... def __str__(self):

... return "ok, I am here"

...

>>> x=A()

>>> print x

ok, I am here

>>> print repr(x)

A()

>>> b = eval(repr(x))

>>> b

A()

>>>

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"

>>> 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"

...

ok

>>> if dog == 0 : print "ok"

[email protected] 151�,�152� Python ÆS)P

Page 60: 强烈推荐Ann77+python

� Python0�

...

ok

>>>

ùã�è�´`²__cmp__ �^{§Ù¢ù´é·Ï��ã�è§�Úêik�oÐ'��? ¦�´`²python��óA:§Ò�Ƭ���ó§���¬�ÃÔg"• __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()

[email protected] 152�,�152� Python ÆS)P

Page 61: 强烈推荐Ann77+python

§1.13 a

>>> len(obj)

Traceback (most recent call last):

File "<stdin>", line 1, in ?

AttributeError: EmptyClass instance has no attribute ’__len__’

>>> class Dog :

... 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 �¬¦^ù����Æ"

[email protected] 153�,�152� Python ÆS)P

Page 62: 强烈推荐Ann77+python

� Python0�

>>> class A:

... def __getitem__(self,key):

... print "debug: key is %s"%key

... if key >=0 and key <=5: return key * key

... 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 �é"

[email protected] 154�,�152� Python ÆS)P

Page 63: 强烈推荐Ann77+python

§1.13 a

• __setitem__(self,key,value)§�[ obj[key]=value"

>>> class A:

... def __setitem__(self,key,value):

... 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) ´aq�"5¿XJvk�½þ�½ö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

[email protected] 155�,�152� Python ÆS)P

Page 64: 强烈推荐Ann77+python

� Python0�

None

>>> print a[:]

you want to get the slice 0:2147483647

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

>>>

• Ù¦�âö�Î

[email protected] 156�,�152� Python ÆS)P

Page 65: 强烈推荐Ann77+python

§1.14 É~?n(exception)

�{ (J__add__(self,other) self + other

__sub__(self,other) self - other

__mul__(self,other) self * other

__div__(self,other) self / other

__mod__(self,other) self % other

__divmod__(self,other) divmod(self,other)

__pow__(self,other) self ** other

__pow__(self,other,modulo) pow(self,other,modulo)

__lshift__(self,other) self << other

__rshift__(self,other) self >> other

�kéõ§�´·�)P�´Ø����ë�Ãþ��"o�§kéõ¼ê¢yö�έ1�Å�§A�¤k�python ö�ÎÑkù«­1Å�"\�±���gC�class§4¦wå5§���list §dictionary ��§|±¤k�list �¤k�ö�ÎÚ�é"3python �module lib ¥®²kù��class§�±w¦�� �è§�~�á§�´ékd�"3lunix ¥�±3/usr/lib/python2/ ¥é�UserList.py UserDict.py"

§1.14 É~?n(exception)

§1.14.1 �o´É~?n§��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()

{

...

if ( open(...) == -1 ){

return -1;

}

...

}

int fun2()

[email protected] 157�,�152� Python ÆS)P

Page 66: 强烈推荐Ann77+python

� Python0�

{

...

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

}

ùã§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£ã"

[email protected] 158�,�152� Python ÆS)P

Page 67: 强烈推荐Ann77+python

§1.14 É~?n(exception)

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�«´

try :

... # statements 1

except ExceptionType :

... # statements 2

£ãXe:

• Äk�1statement 1§XJvkexception u)§@oÒ���~§Ò�vktry �é��§UY�1�¡��é"

[email protected] 159�,�152� Python ÆS)P

Page 68: 强烈推荐Ann77+python

� Python0�

• 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")

except IOError:

print "can not open file"

else:

for i in f.readlines(): print i

L«XJ�m©�¤õ§�Ò´`§�m©���ÿvku)É~ÒÖ©�"ÏL'�±eA�~f§�±��ù���Ð?"

try:

f = open("/home/chunywang/tmp/test.py","r")

[email protected] 160�,�152� Python ÆS)P

Page 69: 强烈推荐Ann77+python

§1.14 É~?n(exception)

for i in f.readlines(): print i

except IOError:

print "can not open file"

ù�~fréõ�éÑ�3try ¥§ù���{§¬�5¯K§XJÑyIOError§�Ø�½´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"

,��'��~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

[email protected] 161�,�152� Python ÆS)P

Page 70: 强烈推荐Ann77+python

� Python0�

ù«�{¥§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�ß"1�«É~?n��{´

try:

... # statements 1

finally:

... # statements 2

ù«�ªØUÚ1�«�ª·^§�Ò´`§ØU�kexcept Úelse §�Ðr§w¤��,�«�é"ÃØ´Äu)exception §�´return �é�£§finallyféstatements 2Ѭ�1§

[email protected] 162�,�152� Python ÆS)P

Page 71: 强烈推荐Ann77+python

§1.14 É~?n(exception)

>>> 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

3except ¥��exceptionTypeÚobject �a.��§Ò�±Ó¼ù�exception "a.���¿g´�object ´�a.���instance"XJ��object ¤á�class U«Ù¦�class§@où�object �±´õ�a.�instance§ùa.�)object ¤á�class �Ia§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Ãþ¥�±

[email protected] 163�,�152� Python ÆS)P

Page 72: 强烈推荐Ann77+python

� Python0�

��éõException �a.§X: KeyError§IndexError§IOError ����"�´python�óvk��§\�±�Ñ?Ûa.�é�"^r�±gCMï��Exception �fa§5L«^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���§@´éßÔ�§��§L¤<åÔå�¯�"

�uÑ�?n§�±3±�O\§Ï�¼ê��£�ÚÑ�?nvk'X§§S�ÌZ´ØI�UC�§§S�?n6§ØI�Cz"�Ò´`§�¢�ÌN(�´Ø^C�§���´V<\�"·�xx�´kÓ���n§Ñ´kx�Ó+§,�2�Ú�Ú[z"

XJvkexception Å��{(~XC�ó)§\ÒI�trace (|¢) �.´=�¼ê�£�ا �´�Ø� Þ§,�3¤kN^ù�¼ê�/�Ñ\�ä§þ��Ø�§XJk¼ê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�é"Ò�´��è§

[email protected] 164�,�152� Python ÆS)P

Page 73: 强烈推荐Ann77+python

§1.14 É~?n(exception)

@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§VBScript §Java Script §Bash"X�.mu( 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"

[email protected] 165�,�152� Python ÆS)P

Page 74: 强烈推荐Ann77+python

� muPython ¦^�óä

111���ÙÙÙ

mmmuuuPython ¦¦¦^���óóóäää

§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

[email protected] 166�,�152� Python ÆS)P

Page 75: 强烈推荐Ann77+python

§2.1 ¦^Emacs ?6Python §S

(setq auto-mode-alist

(cons ’("\\.py$" . python-mode) auto-mode-alist))

(setq interpreter-mode-alist

(cons ’("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 ��§?6python �èÒk�Ø^ÆÒ¬�éÐ�A5"~Xµ

• 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�Ð?Ò´§ÃØ^�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 )ºì"

[email protected] 167�,�152� Python ÆS)P

Page 76: 强烈推荐Ann77+python

� muPython ¦^�óä

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«�aq"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�¬"ù���Jpmu�Ý"ù�·-Ú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

[email protected] 168�,�152� Python ÆS)P

Page 77: 强烈推荐Ann77+python

§2.2 Ù¦?6ì

C-M-e ½ö M-x py-end-of-def-or-class

©OL«£Ä1I���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-x5u�region�mÞÚ(�"Ó��±¦^ëê"ù�·-A�3Emacs ¤k�?§�ª¥å�^"

10. C-c > ½ö C-c C-r ½ö M-x py-shift-region-right

C-c < ½ö C-c C-l ½ö 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ý�Ø�"

[email protected] 169�,�152� Python ÆS)P

Page 78: 强烈推荐Ann77+python

� muPython ¦^�óä

§2.3 NÁ§SNÁ§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��§¦¦^.��NÁóä§;.�Ò´GDB "

�Ú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” ��¤�“byFull Path Name”§��±�U ?�Ú´Äw«1Ò��"

6. ÀJFile/Open èü§�m\�� §S§Ò�±NÁ"

Ï�´ã/.¡§äN�NÁ�{§¹¢�¬��Ò¬"

[email protected] 170�,�152� Python ÆS)P

Page 79: 强烈推荐Ann77+python

111nnnÙÙÙ

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

[email protected] 171�,�152� Python ÆS)P

Page 80: 强烈推荐Ann77+python

n Python �~^�¬

help(obj) 3��ϧobj �±´��?Ûa."callable(obj) ww��obj´Ø´�±�¼ê��N^

¦"repr(obj) ��obj �L«iÎG§�±|^ù�iÎ

G^eval ¼ê­ïTé������eval(str) str´��iÎG§L«Ü{�python L�

ª"�£ù�L�ªdir(obj) �wobj �name space ¥���name "hasattr(obj§name) w�w��obj �name space ¥´Ä

knamegetattr(obj§name) ����obj�name space¥���name"setattr(obj§name§value) ���obj �name space ¥�name �

�valueù�objectdelattr(obj§name) lobj �name space ¥íØ���namevars(obj) � £ � �object �name space"

^dictionary L«locals() �£��ÛÜname space§^dictionary L

«globals() �£���Ûname space§^dictionary L

«type(obj) �w��obj �a.isinstance(obj§cls) wwobj´Ø´cls�instanceissubclass(subcls§supcls) 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

[email protected] 172�,�152� Python ÆS)P

Page 81: 强烈推荐Ann77+python

§3.1 S��¬

>>> 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’)

[email protected] 173�,�152� Python ÆS)P

Page 82: 强烈推荐Ann77+python

n Python �~^�¬

chr(i) r��ASCII ê�§C¤iÎord(i) r��iνöunicodeiΧC¤ASCII ê�oct(x) r�êx C¤l?�L«�iÎGhex(x) r�êx C¤�8?�L«�iÎGstr(obj) ��obj �iÎG£ãlist(seq) r��sequence =�¤��listtuple(seq) r��sequence =�¤��tupledict()§dict(list) =�¤��dictionaryint (x) =�¤��integerlong(x) =�¤��long integerfloat(x) =�¤��2:êcomplex(x) =�¤Eêmax(... ¦���min(...) ¦���

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)

[email protected] 174�,�152� Python ÆS)P

Page 83: 强烈推荐Ann77+python

§3.1 S��¬

>>> 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

[email protected] 175�,�152� Python ÆS)P

Page 84: 强烈推荐Ann77+python

n Python �~^�¬

[’__builtins__’, ’__doc__’, ’__module__’, ’a’, ’abc’]

>>> x=A()

>>> x.abc() #¤õok

>>>

ù«�ª´é(¹Úr��§�´¦éJ�Ȥ�C++ ½öJava �ó"Ø�§\(½^Python ��§Smu�ÌN�ó§ �éPython �5Uék&%§Ø�^Ù§�óXC++ ­�,õU�¬"��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\ߧ¤éõåí§5UvkUCõ�§� ØØv�ó§python kprofilemodule ^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’"

[email protected] 176�,�152� Python ÆS)P

Page 85: 强烈推荐Ann77+python

§3.1 S��¬

>>> 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 tottime percall cumtime percall filename:lineno(function)

1 0.090 0.090 0.250 0.250 <string>:1(?)

10000 0.160 0.000 0.160 0.000 abc:1(?)

1 0.000 0.000 0.250 0.250 profile:0(for i in

range(10000): exec c)

0 0.000 0.000 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

^

[email protected] 177�,�152� Python ÆS)P

Page 86: 强烈推荐Ann77+python

n Python �~^�¬

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 � �dictionary§ � ¹ � ¸ C þ � N � 'X"os.environ["HOME"] �±���¸CþHOME��"

os.chdir(dir) UC�c8¹os.cwd() ���c8¹os.getegid() ��k�|idos.getgid() ��|idos.getuid() ��^ridos.geteuid() ��k�^ridos.setegid() ��k�|idos.setgid() ��|idos.setuid() ��^ridos.seteuid() ��k�^ridos.getgroups() ��^r|¶¡�Los.getlogin() ��^r�¹¶¡os.getenv ���¸Cþos.putenv ���¸Cþos.umask ��umask

L 3.2-3: XÚN^Þ~

�õ§L3.2-3 ==�Ñ��Ü©"��U���XÚN^§3python¥ÑUé�"

[email protected] 178�,�152� Python ÆS)P

Page 87: 强烈推荐Ann77+python

§3.2 Úö�XÚ�'�N^

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�?§"

[email protected] 179�,�152� Python ÆS)P

Page 88: 强烈推荐Ann77+python

n Python �~^�¬

�)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

[email protected] 180�,�152� Python ÆS)P

Page 89: 强烈推荐Ann77+python

§3.2 Úö�XÚ�'�N^

#´ÎÒë�íº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´�o"os.path.walk ¬rH{p e�¤kf8¹§�)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 eATaq"

§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()

[email protected] 181�,�152� Python ÆS)P

Page 90: 强烈推荐Ann77+python

n Python �~^�¬

’’

ùã�è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§´�

[email protected] 182�,�152� Python ÆS)P

Page 91: 强烈推荐Ann77+python

§3.3 regular expression

�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

>>>

ùp0���{ü�^{§Ä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 match

[^] is match

[$] is match

[*] is match

[email protected] 183�,�152� Python ÆS)P

Page 92: 强烈推荐Ann77+python

n Python �~^�¬

[+] is match

[?] is match

[{] is match

[\] is not match

[|] is match

[(] is match

[)] is match

���õêmetacharacter 3[]¥ÑÚ����§�´ko�metacharacter ØÚ����§@Ò´“^[]\”§�¡¬����`²§^ L«��§�¡0�§[]XJÑy3[]¥§Ò¬©Ø�Ù=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 [0-9]

\D [^0-9]

\s [ \t\n\r\f\v]

\S [^ \t\n\r\f\v]

\w [a-zA-Z0-9_]

\W [^a-zA-Z0-9_]

\t L«Útab ��§Ù¦�ÑÚiÎG�L«{��\x20 L«Ú�8?�ascii 0x20 ��

k\ §�±3[] ¥L«?ÛiÎ"5¿§üÕ���“.” XJvkÑy[]¥§L«Ø�1\n ±���?ÛiÎ"aq[^\n]"

[email protected] 184�,�152� Python ÆS)P

Page 93: 强烈推荐Ann77+python

§3.3 regular expression

§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"��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Î� �"XJ�����§@oÒ3*§+§?§{m,n} �¡\��?§C¤*?§+?§??§{m,n}?L«����"

§3.3.4 ¦^�©iÎG

·���§iÎGL«��{¥^\\ L«iÎ\§ 3regexp ¥�þ�¦^\§¤±3regexp¥Ñy�þ\\ù�K��Ö5§�3regexp ¥��\ I�ù��re.compile("\\\\") ù�¬éæ�")ûù�¯K��{´µ3iÎGc¡\��r

L«raw �ª§\�AÏ�^ÒØ�"¤±3python L«regexp��Ñ^\r��{"~X

>>> a=r"\a"

>>> print a

\a

>>> a=r"\"a"

>>> print a

\"a

>>>

§3.3.5 ¦^re �¬

¦^regexp§Ï~^±eA�Ú½µ

[email protected] 185�,�152� Python ÆS)P

Page 94: 强烈推荐Ann77+python

n Python �~^�¬

• k^re.compile ����RegexObject§L«��regexp"• ,�^pattern �match§search��{§��MatchObject"• 2^match object ����� �§���iÎG�&E"

RegxObject �~^¼ê:

• RE_obj.match(str,[pos[,endpos]])§XJstr�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

>>>

[email protected] 186�,�152� Python ÆS)P

Page 95: 强烈推荐Ann77+python

§3.3 regular expression

• 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"

>>> for m in re.compile("[ab]").finditer("tatbxaxb"):

... print m.span()

...

(1, 2)

(3, 4)

(5, 6)

(7, 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�>.§3Ç�¥§c�>.´éJ.½�§�´3=�¥I:ÎÒ§����Ñ�±L«��üc�>.§Ù¦�ó�kaq§äNXÛ.½§dlocale û½"~X\binfo\b �¬��“info” ج��“information”"�´�5¿e¡�~f"

[email protected] 187�,�152� Python ÆS)P

Page 96: 强烈推荐Ann77+python

n Python �~^�¬

>>> print re.compile(r"\binfo\b").match("info ") #¦^ raw �ª<_sre.SRE_Match object at 0x817aa98> #\b L«üc>.>>> print re.compile("\binfo\b").match("info ") #vk¦^ raw �ªNone #\b L«ò�ÎÒ>>> print re.compile("\binfo\b").match("\binfo\b ")

<_sre.SRE_Match object at 0x8174948>

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: [email protected]

name: Ann

Address: BUPT

telephone: 62284321

email: [email protected]

^�1©mP¹"@Ò���Charles §Ann �¶¡Ü©§BUPT �/�Ü©��"XÛ)ûù�¯KQ? Group ! we¡�~f"

>>> x="""

... name: Charles

... Address: BUPT

... telephone: 62281234

... email: [email protected]

...

13lex ¥§“abc” ����Ý'“abc” ��

[email protected] 188�,�152� Python ÆS)P

Page 97: 强烈推荐Ann77+python

§3.3 regular expression

... name: Ann

... Address: BUPT

... telephone: 62284321

... email: [email protected]

... """

>>> 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, [email protected]

here is your friends list

Ann, BUPT, 62284321, [email protected]

ù�~fk:E,§�´ATvk�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§éØ�Ù§ �XJ3O\��group �{§ÒI�N��¡¤k�group �Òè"XJU^m.group(’name’) 5L«name �{§@oÒ�ßõ"ù�¯K´ù�)û�§we¡�~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):

[email protected] 189�,�152� Python ÆS)P

Page 98: 强烈推荐Ann77+python

n Python �~^�¬

... print m.groups()

(’ Charles’, ’ BUPT’, ’ 62281234’, ’ [email protected]’)

(’ Ann’, ’ BUPT’, ’ 62284321’, ’ [email protected]’)

>>> 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’)

[email protected]

>>> matchs[1].group(’name’)

’ Ann’

>>> matchs[1].group(’address’)

’ BUPT’

>>> matchs[1].group(’telephone’)

’ 62284321’

>>> matchs[1].group(’address’)

’ BUPT’

>>> matchs[1].group(’email’)

[email protected]

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¿vkregexp �Ü©"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�"

[email protected] 190�,�152� Python ÆS)P

Page 99: 强烈推荐Ann77+python

§3.4 ^struct�¬?n�?�êâ

DOTALL§S 4. ��?¿iΧ�)�1Î\n

IGNORECASE§I �Ñ���LOCALES§L 4\w!\W!\b!\B Ú�clocale��

MULTILINE§M õ1�ª§�K�^Ú$

VERBOSE§X 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 ....WAVE

[email protected] 191�,�152� Python ÆS)P

Page 100: 强烈推荐Ann77+python

n Python �~^�¬

��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¿�/�"

�ª C �óa. Python a.x char Ã(L«W¿i!)c char �Ý�1�iÎGb signed char IntegerB unsigned char Integerh signed short IntegerH unsigned short Integeri signed int IntegerI unsigned int Integerl signed long IntegerL unsigned long Integerq signed long IntegerQ unsigned long Integerf float Floatd double Floats char[] Stringp char[] StringP void* Integer

L 3.4-4: struct �¬¥��ª½Â

[email protected] 192�,�152� Python ÆS)P

Page 101: 强烈推荐Ann77+python

§3.5 ^Cmd �¬?�{ü�·-1��

iÎ i!^S �ÝÚéà�ª@ native native= native standard< little-endian standard> big-endian standard! network (= big-endian) 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�ÿÁ§½ö��Ò¦^ù«��§���ª�¬"

[email protected] 193�,�152� Python ÆS)P

Page 102: 强烈推荐Ann77+python

n Python �~^�¬

�¯�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"

C-a £Ä�1ÄC-e £Ä�1�C-u íØ�1ÄC-w íØþ��c�C-y ÊbíØ�SNC-f ��£Ä���C-b �m£Ä���M-f ��£Ä��ücM-b �m£Ä��üc

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 �faclass CmdInterface(Cmd):

# ½Â��·-# argc ´ù�·-�·-1ëêdef do_say_hello(self,argc):

print "hello! " + argc

if __name__=="__main__" :

# welcome ½ÂXÚ��H&Ewelcome ="welcome a simple command interface demo demo"

# ?\·-)º�Ì�§Ö��·-¿�)º�1"CmdInterface().cmdloop(welcome)

$1(J:

[email protected] 194�,�152� Python ÆS)P

Page 103: 强烈推荐Ann77+python

§3.5 ^Cmd �¬?�{ü�·-1��

%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

þ¡�§Sk��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” òÑ"

[email protected] 195�,�152� Python ÆS)P

Page 104: 强烈推荐Ann77+python

n Python �~^�¬

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” �Uügtab §Ò¬Ñy

Charles Smith Tom

^uJ«^rÖà�·-"XJÑ\“C” ,�Utab �§Ò¬gÄÑ\“Charles”"

complete_say_hello==^usay_hello�·-�gÄÖàõU"textL«^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øUCIOÑ\ÚIOÑÑ�Ŭ""���¹e§¦�©O´sys.stdin Úsys.stdout"

[email protected] 196�,�152� Python ÆS)P

Page 105: 强烈推荐Ann77+python

§3.5 ^Cmd �¬?�{ü�·-1��

§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. Ñ \“ help say hello” Ò ¬ �1help_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"

[email protected] 197�,�152� Python ÆS)P

Page 106: 强烈推荐Ann77+python

n Python �~^�¬

§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§Ò´vké���func �u�§XJU�äcallable(func) Ò¬�ЧØ,§fa½Â�do_cmd �´¤¼ê§ ´¤Cþ§@oÒ¬�)É~"

Ó�§�Ï&E�)¤§�¦�Îhelp_cmd �ª�¤¼ê"

�Ï�©a�´Úgetattr k'X"

• Undocumented commands:kdo_cmd �ª�¤¼ê§�´vkhelp_cmd �ª�¤¼ê"

• Documented commands:kdo_cmd �ª�¤¼ê§�khelp_cmd �ª�¤¼ê"

[email protected] 198�,�152� Python ÆS)P

Page 107: 强烈推荐Ann77+python

§3.6 ?n·-1À�

• 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 ?

[email protected] 199�,�152� Python ÆS)P

Page 108: 强烈推荐Ann77+python

n Python �~^�¬

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«vk)º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À���¡���kÒL«ù�À�I�ëê"~Xµþ���~f¥�getopt U�"

getopt(sys.argv[1:],"a:","all")

XJ·-1¥vkJøÀ�§��¬�ÑGetoptErrorÉ~"$1(J:

[email protected] 1100�,�152� Python ÆS)P

Page 109: 强烈推荐Ann77+python

§3.6 ?n·-1À�

%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")

[email protected] 1101�,�152� Python ÆS)P

Page 110: 强烈推荐Ann77+python

n Python �~^�¬

(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ëê)

[email protected] 1102�,�152� Python ÆS)P

Page 111: 强烈推荐Ann77+python

§3.6 ?n·-1À�

%ls -l /usr

Ù¥-l usr Ò´·-1ëê"sys.argv ´��list §^uL«·-1"~f¥§sys.argv Ò´

[’ls’,’-l’,’/usr’]

·-1ëêÒ´sys.argv[1:] §Ï�sys.argv[0] L«·-��"• option (·-1À�)§S3�1��ÿ§largument ��&E§^5N�§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 §�þ¡aq§Òvk�{©�Ù-file ´��À��´-f -i -l -e o�À�º

• ^\Ò§�O~Ò§X+f §+rgb §ØÜS."• ^�m�O~Ò§~X/l §/rgb §ù´Windows ÚVMS �^{§�´3Unixe�mL«8¹§¤±ls /l— Ò©Ø�Ù´/l ´À�§�´8¹¶¡"

• option augument(À�ëê)�-f outputfile ù��À�§�¡���ëê§outputfile §L«À��ëê"-foutputfile Ú-f outputfile Ñ��"k�À�ØI�ëê§k�À�7L�Ñëê"´Ä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 "

[email protected] 1103�,�152� Python ÆS)P

Page 112: 强烈推荐Ann77+python

n Python �~^�¬

• 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"

[email protected] 1104�,�152� Python ÆS)P

Page 113: 强烈推荐Ann77+python

§3.6 ?n·-1À�

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¦'��oQ? join ´rü�©�Ü¿§¤±7L�Ñü�©�¶¡"tr ´�ÈõU§7L`²r�o�Ȥ�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ø�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 "

[email protected] 1105�,�152� Python ÆS)P

Page 114: 强烈推荐Ann77+python

n Python �~^�¬

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¤�

[email protected] 1106�,�152� Python ÆS)P

Page 115: 强烈推荐Ann77+python

§3.6 ?n·-1À�

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" $1(J:

% ./optparser.help.py --help

usage: optparser.help.py [options] arg1 arg2

options:

[email protected] 1107�,�152� Python ÆS)P

Page 116: 强烈推荐Ann77+python

n Python �~^�¬

-h, --help show this help message and exit

-v, --verbose make lots of noise [default]

-q, --quiet be vewwy quiet (I’m hunting wabbits)

-fFILE, --file=FILE write output to FILE

-mMODE, --mode=MODE 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"

(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:

$1(J:

$./opt.group1.py --help

usage: opt.group1.py [options] arg1 arg2

options:

-h, --help show this help message and exit

-v, --verbose make lots of noise [default]

-q, --quiet be vewwy quiet (I’m hunting wabbits)

-fFILE, --file=FILE write output to FILE

-mMODE, --mode=MODE interaction mode: one of ’novice’,

’intermediate’[default], ’expert’

Dangerous Options:

[email protected] 1108�,�152� Python ÆS)P

Page 117: 强烈推荐Ann77+python

§3.7 'u�m��¬

Caution: use these options at your own risk. It is

believed that some of them bite.

-g Group option.

$

`²:

(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] "

§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 ²L0 ¦"3UNIX XÚ¥§epoch ��m´1970c1 �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 ��Ï"

[email protected] 1109�,�152� Python ÆS)P

Page 118: 强烈推荐Ann77+python

n Python �~^�¬

• UTC (Coordiated Universal Time) §�¥Ú��m§½ö`GMT (Greenwich MeanTime) ��%£�m§• DST( Daylight Saving Time) §L«g-�§C �¥¼ê�±?ng-�§äNNo�§´�âØÓ/«���k'X§��k��XÚ©�§^u£ãg-��5K"��XÚ+nAT®²�Ðù�©�"gmtime() , localtime(), strptime() ��£�§�kasctime(), mktime() ,strftime() �ëêÑ´��tuple §Ù¥¹k9 ��ê"ù�9 ��ê�¹ÂXL??

¢Ú� á5 ��0 tm_year X19931 tm_mon 1 – 122 tm_mday 1 – 313 tm_hour 0 – 234 tm_min 0 – 595 tm_sec 0 – 616 tm_wday 0 – 6, Monday is 07 tm_yday 1 – 3668 tm_isdst 0, 1 or -1

L 3.7-7: L«�m�

��¼ê�m�'X"ã3-1`²��¼ê�m�'X"

seconds(local)

time

seconds(UTC)

struct time(local time) struct time(UTC)

string

ctime

localtime mktimegmtime

-timezone

+timezone

strftime

strptime

ã 3-1: �m¼ê�m�'X

[email protected] 1110�,�152� Python ÆS)P

Page 119: 强烈推荐Ann77+python

111oooÙÙÙ

Tkinter ???§§§

§4.1 Tkinter0�

§4.1.1 �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"

[email protected] 1111�,�152� Python ÆS)P

Page 120: 强烈推荐Ann77+python

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"

�o´Widget ? Widget ´Button(UÜ) §Canvas(xÙ) §Menu(èü) §Label(ü1I\) §Message(õ1I\) §Listbox(�L) §Entry (ü1Ñ\µ) §Frame(µe)§Radiobutton(õ«À��üÀµ) §CheckButton(EÀµ) §Scrollbar(EÄ^) §Text(õ1©�Ñ\µ) §Scale(3�½��SÀJ��ê��EÄ^) TopLevel(I�)���Ú¡"

�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

[email protected] 1112�,�152� Python ÆS)P

Page 121: 强烈推荐Ann77+python

§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´��ÊÏ

[email protected] 1113�,�152� Python ÆS)P

Page 122: 强烈推荐Ann77+python

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 ��ª"

[email protected] 1114�,�152� Python ÆS)P

Page 123: 强烈推荐Ann77+python

§4.3 Widget ���

§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 �masterwidget§XJ\éB�{§$�ëmaster widget ��±Ø^�½§Tkinter ¬^�C¦^L�master widget ��%@�master widget "

• w.cget(option) ����widget �option ��"w ´��widget "¤k�widgetclass Ñkr__getitem__ N��w.cget þ§¤±¦�ü�vk�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:

w.config(text="xxx")

[email protected] 1115�,�152� Python ÆS)P

Page 124: 强烈推荐Ann77+python

o Tkinter ?§

¤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.keys()w.config(optionname=optionvalue,...) w[’optionname’]=optionvaluew.cget(’optionname’) w[’optionname’]

äN¦^@«d�<S.û½§·ú�1�«�ª�Ð"

§4.4 Geometry Manager(AÛ+nì)

�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§Whatyou 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é{"

^Geometry Manager §\I�^�ëêw�¦\����JÒ�±§�½´\���"

��Tk kn«Geometry Manager :1�N\�"{*:Ú·Ø��"

[email protected] 1116�,�152� Python ÆS)P

Page 125: 强烈推荐Ann77+python

§4.4 Geometry Manager(AÛ+nì)

• 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§,�2rslave 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§û½slavewidget N�UCgC���§5·Aparcel ���"

anchor L«3parcel ¥��slave widget ��ª"�±´±e��""��´CENTER"

[email protected] 1117�,�152� Python ÆS)P

Page 126: 强烈推荐Ann77+python

o Tkinter ?§

W ���� E �m��N �þ�� S �e��NW ��þ�� NE �mþ��SW ��e�� SE �me��CENTER �3�¥m

ùp��5¿�´§XJfill ��´X §@oanchor ´W ÚE Ò䢧Ï�slavewidget �°Ý®²´��§����´�m�Òvk�o¿Â"Ó��n§XJfill��´Y §@oanchor ´N ÚS Òä¢"XJfill ��´BOTH §@oanchoroption Ò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�'XXJr¤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÷=��>´dsideoption �½�"

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 option5UC¤kparcel ���"XJexpand option ´0 §@oÒ�§Ò4@��

[email protected] 1118�,�152� Python ÆS)P

Page 127: 强烈推荐Ann77+python

§4.4 Geometry Manager(AÛ+nì)

/��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 §��o´ü�? ´Ï��mÑI�3Ñipadx�ål§Ó�þe�ÑI�õ3Ñ5ipady�ål"�´XJfilloption��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 �>.Úslavewidget �>.�mo´�3Ñ5padx Úpady @oõ��x�m"

��Ð��slave widget �§pack +nì¬~�parcel §�e��'���cavity ^5��e��slave widget"XJcavity ��mØ����slave widget §@où�slavewidget ¬Óâ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��"�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 §^ur�|widget w¤��widget"

[email protected] 1119�,�152� Python ÆS)P

Page 128: 强烈推荐Ann77+python

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 wid-get"

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 "

XJü��|Ü´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 "

[email protected] 1120�,�152� Python ÆS)P

Page 129: 强烈推荐Ann77+python

§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�¤"

[email protected] 1121�,�152� Python ÆS)P

Page 130: 强烈推荐Ann77+python

o Tkinter ?§

Place +nì

Place �±°(�����slave widget � �Ú��§aquVB ¥�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 5UC��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, SystemBack-ground, SystemButtonFace, SystemButtonHighlight, SystemButtonShadow, SystemBut-tonText, SystemCaptionText, SystemDisabledText, SystemHighlight, SystemHighlightText,SystemInactiveBorder, SystemInactiveCaption, SystemInactiveCaptionText, SystemMenu,SystemMenuText, SystemScrollbar, SystemWindow, SystemWindowFrame, SystemWin-dowText.

3Macintosh ¥§�±¦^e¡�XÚôÚ:

SystemButtonFace, SystemButtonFrame, SystemButtonText, SystemHighlight, Sys-temHighlightText, SystemMenu, SystemMenuActive, SystemMenuActiveText, System-MenuDisabled, SystemMenuText, SystemWindowBody.

[email protected] 1122�,�152� Python ÆS)P

Page 131: 强烈推荐Ann77+python

§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

[email protected] 1123�,�152� Python ÆS)P

Page 132: 强烈推荐Ann77+python

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, ÚTimesN��²����iNL��ªþ§ �§XJiNN��}�{§�¬é���bC�iN5�O"¤±3�½iN��ÿTk 8.0 l5Ñج�w�Ø�"XJéØ��bC�iN§@oÒ´^%@iN"�´Tk @��bC�iN§k��ÿ¿Ø´\���§¤±Ø�Lõ���ù�A5"

Windows e�Tk 4.2 �|±ù«iN�L��ª"

¦^tkFont �Font a5�½iN

Ø^iN£ãÎ(font descriptor) £ãiN�§��±ÏLtkFont 5�½iN"Font �¬¥�tkFont a§�±^5�½iN"?ÛTkinter I�iN�ëê§\Ñ�±^tkFont 5�½"~X:

[email protected] 1124�,�152� Python ÆS)P

Page 133: 强烈推荐Ann77+python

§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 �iN´myfont ¤£ã�iN"ù�k��Ð?´§XJ¦^myfont.config(size=40) §@o¤k¦^myfont ��iN�widget �iNÑgÄ�#§â���font propagate "é¤"ù�3§S¥§�±��|aq�widget �½iNmyfont §,���?Umyfont @où�|widget �iNѬ�#"

tkFont.Font |±option XL4.5-1:

Option a. £ãfamily string iNx¶¡size integer iN��§ü point §XJ´Kê§ü ´pixelweight constant NORMAL �´BOLD §%@´NORMAL.slant constant NORMAL �´ITALIC §%@´NORMAL.underline flag 1 �ey�"0 Ø�ey�"overstrike flag 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"

[email protected] 1125�,�152� Python ÆS)P

Page 134: 强烈推荐Ann77+python

o Tkinter ?§

slant�±´RL«Roman §�~"½öIL«�N"½öOL«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��ª�ȤWindowse½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 >µ

¦+kWidget�>µ3%@��¹e´wØ��§�´¤k�Widget Ñk��>µ">µ�)3D �Relief( 2H) �JÚFocus Highlight( �:pw)«�"

relief option ^5L«XÛ±���Widget �>µ"�±´SUNKEN RAISEDGROOVE 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 High-light Region �ôÚ§��Úwidget ����µÚ"highlightthickness L«Focus HighlightRegion �°Ý"��´1 ½ö2 §��ÒØÐw"

ùpk��~f§^5`²>µÚFocus Highlight Region �^{"

# border1.py

[email protected] 1126�,�152� Python ÆS)P

Page 135: 强烈推荐Ann77+python

§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-3"

ã 4-3: border1.py �$1(J

[email protected] 1127�,�152� Python ÆS)P

Page 136: 强烈推荐Ann77+python

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

[email protected] 1128�,�152� Python ÆS)P

Page 137: 强烈推荐Ann77+python

§4.5 Widget ��ª

mainloop()

$1(JXã4-4"

ã 4-4: cursor1.py �$1(J

�àI£Ä�z��ØÓ�UÜþ§àI�/GÒ¬C¤ØÓ�/G"

[email protected] 1129�,�152� Python ÆS)P

Page 138: 强烈推荐Ann77+python

o Tkinter ?§

§4.6 ¯�Ú¯���½

�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>

[email protected] 1130�,�152� Python ÆS)P

Page 139: 强烈推荐Ann77+python

§4.6 ¯�Ú¯���½

0�àI��½Â3X windows ¥��k5 �àI��½Â§��´1 �� 2 ¥�

3 m� 4 E¶þE5 E¶eE

���^1 , 2 , 3 n��"

�´Ø��´�¤ØC�§�±^xmodmap ·-UC"

xmodmap -pp

�±w��càIU��½Â"

3�wu)�o¯���ÿ§±eóä´ék^�"xmodmap �wÚ?UX ���N�'XÚàIN�'X"xev ^5�w¯��"

modifier L«u)àI½ö��¯���ÿ§Ó�UeÙ¦�§Xcontrol §alt§win(super) ���§½ö��¯�3á�mS­Eõg"

modifier �±´Control Mod2, M2Shift Mod3, M3Lock Mod4, M4Button1, B1 Mod5, M5Button2, B2 Meta, MButton3, B3 AltButton4, B4 DoubleButton5, B5 TripleMod1, M1 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

[email protected] 1131�,�152� Python ÆS)P

Page 140: 强烈推荐Ann77+python

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ØÓ��g"z���g��±kõ�¯�?n¼ê?nÓ��¯�"

�±3o�ØÓ�g¥�½¯�"

• widget instance ?�½,��widget instance �¯��½"�k3¯�u)3,���½�widget ��ÿ§â¬Ó¼¯�"�½�{´w.bind(...) §w ´��widget instance "

[email protected] 1132�,�152� Python ÆS)P

Page 141: 强烈推荐Ann77+python

§4.6 ¯�Ú¯���½

<Button-1> ½<1> UeàI��<B1-Motion> UeàI��Ó�£ÄàI"<ButtonRelease-1> º�àI��"<Double-Button-1> 3éá��mS(�~¯��)§àI£Ä�3é��

��S(A�vk£Ä)§ëYUeügàI��"<Enter> àI£Ä�Widget ����S"5¿Ø´Ue

���£��§Enter L«¯��type "<Leave> àIlmWidget ����S"<Return> U e � � � £ � � " ´ � � { � § L

«<KeyPress-Return> "3keysyms ��Ï¥�±��A�¤k���<iÎ�£ã"

<Key> Ue?Û���"a L«Ue���“a” �"<Shift-Up> L«U4���Shift �Ø��Ó�§Ue���¥

�þ�"<Configure> L«Widget ���u)UC��ÿ�¯�"

L 4.6-2: ¯�£ãÞ~

widget �)¯��widget §¤k�¯�event Ѭ��ù�á5"

x,y L«u)¯���ÿ§àI3widget ¥��é �"ü ´pixel

x root, y root L«àI3¶4¥��é �"char a.´string §L«Ú��k'�¯�¥§äNUe

�´=���iÎè"keysym 3Ú��k'�¯�¥§L«U��©i£ã"num 3ÚàIk'�¯�¥§L«àIU�"wight, height L«widget #���"�3configure ¯�¥k�"type L«¯��a."

L 4.6-3: £ã¯��ëê

[email protected] 1133�,�152� Python ÆS)P

Page 142: 强烈推荐Ann77+python

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?Û/�§��UF1 �Ò¬�1�ϧS"

�´XJÓ��¯�3ØÓ�gþ�ºõg��ÿ§TNo�Q? ½ö`��¯�­U��½��ÿ§TNo�º�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¼ê§,��g3widget 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):

[email protected] 1134�,�152� Python ÆS)P

Page 143: 强烈推荐Ann77+python

§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¼ê§Ó��Ê�

[email protected] 1135�,�152� Python ÆS)P

Page 144: 强烈推荐Ann77+python

o Tkinter ?§

N^Ù¦�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

[email protected] 1136�,�152� Python ÆS)P

Page 145: 强烈推荐Ann77+python

§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 CommunicationConventions 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()

[email protected] 1137�,�152� Python ÆS)P

Page 146: 强烈推荐Ann77+python

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-5 5¿§¯�?n¼ê��E|§

ã 4-5: menubar2.py �$1(J

lambda : sys.stdout.write(i)

´Ø1�"

Ï�z��èü�?n¼êÑ´���§Ñ´�<i ��§�o�ÿ\UCi ��§�<�(JÒ¬C"

lambda t = i : sys.stdout.write(i)

[email protected] 1138�,�152� Python ÆS)P

Page 147: 强烈推荐Ann77+python

§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-6

ü�~f�´k«O�"Menubutton ´��ÚButton aq�Àܧ�´¦%@�command Ä�´�Ø��èü"

¦^Menubutton k±eA�Ú½:

1. ïáMenubutton.

mb = Menubutton()

[email protected] 1139�,�152� Python ÆS)P

Page 148: 强烈推荐Ann77+python

o Tkinter ?§

ã 4-6: 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")

[email protected] 1140�,�152� Python ÆS)P

Page 149: 强烈推荐Ann77+python

§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-7

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 §

[email protected] 1141�,�152� Python ÆS)P

Page 150: 强烈推荐Ann77+python

o Tkinter ?§

ã 4-7: 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) )

[email protected] 1142�,�152� Python ÆS)P

Page 151: 强烈推荐Ann77+python

§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-8

ã 4-8: statusbar1.py �$1(J

ù�~f¥�k��w«9§éN´O\��w«9§Ã�Ò´O\��Label "

§4.7.5 IOé{µ

XJÒ´��{ü�Ñ\&E§X��êi§��iÎG§£�´�´Ø´§����

[email protected] 1143�,�152� Python ÆS)P

Page 152: 强烈推荐Ann77+python

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 �±´ABORT, RETRY, IGNORE, OK, CANCEL,YES,½öNOL«%@�^�e§=��UÜ���:"

icon L«¦^�o��IOãI"�±´ERROR, INFO,QUESTION, WARNING

message Ú1��ëêmessage ´��¿g"parent L«é{µ(å��§=��I�C¤�cI�"title Ú1��ëêtitle ´��¿g"type w«=�aUܧ�±´ABORTRETRYIGNORE,

OK, OKCANCEL, RETRYCANCEL, YESNO,YESNOCANCEL"l �è�±w�§z��¼ê®²%@��Ðtype §ù��Ð?´Jp§S��Ö5"

[email protected] 1144�,�152� Python ÆS)P

Page 153: 强烈推荐Ann77+python

§4.7 ~^�A^§S¦^�Widget

{üêâÑ\

3tkSimpleDialg �¬¥§Jø��Ñ\{üêâ�{üé{µ"

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

�±�£��iÎG§XUCancel Uܧ@o�£None

Ù¥µ

title L«I��IK"prompt L«J«^rÑ\&E�©i"options �±´±eÀJ"initialvalue L«Ð©�´�o"parent L«^rÑ\�.�§w«=��I�"

�kaq�tkSimpleDialog.askinteger ÚtkSimpleDialog.askfloat ^{Úþ¡���§XJ^rUCancel §@o�£None ùü�¼ê�kü�option �±ÀJ"minvalueÚmaxvalue ©OL«�����§^u��^r3�½��SÑ\ê�"

�m©��é{µ

tkFileDialog �¬Jøü�¼ê:

tkFileDialog.askopenfilename

tkFileDialog.asksavefilename

�±�£��©�é�§XJ^rUCancel @o�£None "

¦^�{´:

tkFileDialog.askopenfilename(options)

tkFileDialog.asksavefilename(options)

�±¦^�option k:

[email protected] 1145�,�152� Python ÆS)P

Page 154: 强烈推荐Ann77+python

o Tkinter ?§

¶¡ a. £ãdefaultextension string XJ^rvk�Ñ©��*

ж§@oÒgÄ\þù�*ж¡"

filetypes list list ¥�z����´��(label,pattern) �tuple "c ¡ �label ^ u J « ^r ´ � o � � a . � ©�§pattern ^u��©�¶¡"

initialdir string Щ8¹"initialfile string %@©�¶¡"parent widget Óþ"title string 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 L«��ôÚ�§�±´��iÎG§�ÌôÚ½Â��ª§7L´“#rgb” “#rrggbb” “#rrrrggggbbbb”��ª"��±´��tuple Ù¥¹kn���§©OL«RGB �n�ØÓ©þ"ù�ôÚ�Ú1��ëê´��¿g§�²Ð©ôÚ�"

parent Óþ"title I�IK"�£�´��tuple§Ù¥kü���§1��´^tuple L�ôÚ��ª§1��´^

iÎGL�ôÚ��ª"

g½Âé{µ

x �±þé{µØ÷v�¦��ÿ§�±¦^tkSimpleDialog �¬¥Jø�Dialog a"�±�wtkSimpleDialog.py � �è§�Ø´AOE,"

[email protected] 1146�,�152� Python ÆS)P

Page 155: 强烈推荐Ann77+python

§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-9

ã 4-9: inputpassword.py �$1(J

Ù¥­�body ¼ê§Úapply ¼ê"kùü�¼êÒ�±�¤��õU�ö�"body ¼ê^5Mïé{µ¥�z��widget §�´Ø�¹OK ÚCancel UÜ"

[email protected] 1147�,�152� Python ÆS)P

Page 156: 强烈推荐Ann77+python

o Tkinter ?§

apply ¼ê^u�£k^��§����self.result á5§^u�£&E"

3^rUOK UÜ��ÿ§Ò¬N^apply ¼ê��self.result "XJUCancel Uܧself.result Ò´None "

�k��¼êvalidate()�±­�"vk?Ûëê"validate() ù�¼ê^5�ä^rÑ\�&E´Ä÷v�¦§�^rUOK UÜ��ÿ§Ò¬gÄN^ù�¼ê§XJù�¼ê�£1 §L«^rÑ\´÷vÜ6�¦�§ÒN^apply ��self.result ,��£"XJù�¼ê�£0§UOK �Øå�^"�Ð�^r��J«§w�^r��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"

[email protected] 1148�,�152� Python ÆS)P

Page 157: 强烈推荐Ann77+python

111ÊÊÊÙÙÙ

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)

{

[email protected] 1149�,�152� Python ÆS)P

Page 158: 强烈推荐Ann77+python

Ê 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� ó � * : 5w§Python ¥�¼êkü«§�«´~^�^tuple 5D4ëê§��´METH_VARARGSL«§�«´^dictionary 5D4ëê§�� keyword parameter§^METH_VARARGS|METH_KEYWORDSL«"ùü�Macro Ò©OéAùü«¼ê"ü«�ª3C �ó¥éA�¼ê�.´Ø���"

ww·�ý�Z¹�¼êspam_system§ ¦��£�L«Python ¥¼ê��£�§“��Ñ´é�” ùé{3C �ó¥�Ly/ªÒ´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*

[email protected] 1150�,�152� Python ÆS)P

Page 159: 强烈推荐Ann77+python

§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�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�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

[email protected] 1151�,�152� Python ÆS)P

Page 160: 强烈推荐Ann77+python

Ê 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 ��£�>>>

[email protected] 1152�,�152� Python ÆS)P