Attachment 'Py2_5_tut_cn.tex'
Download 1 \documentclass{manual}
2 \usepackage[T1]{fontenc}
3 \usepackage{textcomp}
4 \usepackage{CJK}
5 \usepackage[CJKbookmarks]{hyperref}
6
7 % Things to do:
8 % Should really move the Python startup file info to an appendix
9
10 \begin{CJK*}{GBK}{kai}
11
12 \title{Python Tutorial Python ÈëÃÅÖ¸ÄÏ}
13
14 \author{ ÁõöÎ ÀîÃÎÒÄ £¨Ò룩 }
15 \authoraddress{
16 2006Äê7Ô ÓÚ Öйú¸£ÖÝ \\
17 Email: \email{[email protected]}
18 }
19
20 \date{ 2006-07-14 }
21
22
23 \input{boilerplate}
24
25 \makeindex
26
27 \begin{document}
28
29 \maketitle
30
31 \ifhtml
32
33
34
35 \chapter*{Front Matter ǰÑÔ \label{front}}
36 \fi
37
38
39 \input{copyright}
40
41 \begin{abstract}
42
43 \noindent
44 Python is an easy to learn, powerful programming language. It has
45 efficient high-level data structures and a simple but effective
46 approach to object-oriented programming. Python's elegant syntax and
47 dynamic typing, together with its interpreted nature, make it an ideal
48 language for scripting and rapid application development in many areas
49 on most platforms.
50
51 Python ÊÇÒ»ÖÖÈÝÒ×ѧϰµÄÇ¿´óµÄ±à³ÌÓïÑÔ¡£Ëü°üº¬Á˸ßЧµÄ¸ß¼¶Êý¾Ý½á¹¹£¬Äܹ»Óüòµ¥¶ø¸ßЧµÄ·½Ê½½øÐÐÃæÏò¶ÔÏó±à³Ì¡£Python ÓÅÑŵÄÓï·¨ºÍ¶¯Ì¬ÀàÐÍ£¬ÒÔ¼°ËüÌìÈ»µÄ½âÊÍÄÜÁ¦£¬Ê¹Æä³ÉΪÁË´ó¶àÊýƽ̨ÉϹ㷺ÊÊÓÃÓÚ¸÷ÁìÓòµÄÀíÏë½Å±¾ÓïÑԺͿª·¢»·¾³¡£
52
53 The Python interpreter and the extensive standard library are freely
54 available in source or binary form for all major platforms from the
55 Python Web site, \url{http://www.python.org/}, and may be freely
56 distributed. The same site also contains distributions of and
57 pointers to many free third party Python modules, programs and tools,
58 and additional documentation.
59
60 Python ½âÊÍÆ÷¼°ÆäÀ©Õ¹±ê×¼¿âµÄÔ´ÂëºÍ±àÒë°æ±¾¿ÉÒÔ´Ó Python µÄ Web Õ¾µã, \url{http://www.python.org/},¼°ÆäËùÓоµÏñÕ¾ÉÏÃâ·Ñ»ñµÃ£¬²¢ÇÒ¿ÉÒÔ×ÔÓÉ·¢²¼¡£¸ÃÕ¾µãÉÏÒ²ÌṩÁË
61 Python µÄһЩµÚÈý·½Ä£¿é£¬³ÌÐò£¬¹¤¾ß£¬ÒÔ¼°¸½¼ÓµÄÎĵµ¡£
62
63 The Python interpreter is easily extended with new functions and data
64 types implemented in C or \Cpp{} (or other languages callable from C).
65 Python is also suitable as an extension language for customizable
66 applications.
67
68 Python½âÊÍÆ÷¿ÉÒÔºÜÈÝÒ×µÄͨ¹ýC»òÕß \Cpp{}£¨»òÕ߯äËü¿ÉÒÔͨ¹ýCµ÷ÓõÄÓïÑÔ£©À©Õ¹Ðº¯ÊýºÍÊý¾ÝÀàÐÍ¡£Python Ò²¿ÉÒÔ×÷Ϊ¶¨ÖÆÓ¦ÓõÄÀ©Õ¹ÓïÑÔ¡£
69
70 This tutorial introduces the reader informally to the basic concepts
71 and features of the Python language and system. It helps to have a
72 Python interpreter handy for hands-on experience, but all examples are
73 self-contained, so the tutorial can be read off-line as well.
74
75 ±¾ÊÖ²áÏò¶ÁÕß½éÉÜ Python ÓïÑÔ¼°ÆäϵͳµÄ»ù±¾ÖªÊ¶Óë¸ÅÄî¡£ÅäºÏPython½âÊÍÆ÷ѧϰ»áºÜÓаïÖú£¬²»¹ýËùÓеÄÀý×Ó¶¼ÒѰüÀ¨ÔÚÎÄÖУ¬ËùÒÔÕâ±¾ÊÖ²áÒ²ºÜ¿ÉÒÔÀëÏßÔĶÁ¡£
76
77 For a description of standard objects and modules, see the
78 \citetitle[../lib/lib.html]{Python Library Reference} document. The
79 \citetitle[../ref/ref.html]{Python Reference Manual} gives a more
80 formal definition of the language. To write extensions in C or
81 \Cpp, read \citetitle[../ext/ext.html]{Extending and Embedding the
82 Python Interpreter} and \citetitle[../api/api.html]{Python/C API
83 Reference}. There are also several books covering Python in depth.
84
85 ÐèÒªÓйرê×¼¶ÔÏóºÍÄ£¿éµÄÏêϸ½éÉܵϰ£¬Çë²éѯ\citetitle[../lib/lib.html]{Python ¿â²Î¿¼ÊÖ²á}Îĵµ¡£\citetitle[../ref/ref.html]{Python ²Î¿¼ÊÖ²á}ÌṩÁ˸ü¶àµÄ¹ØÓÚÓïÑÔ·½ÃæµÄÕýʽ˵Ã÷¡£ÐèÒª±àдC»ò\CppÀ©Õ¹£¬ÇëÔĶÁ\citetitle[../ext/ext.html]{Python ½âÊÍÆ÷µÄÀ©Õ¹ºÍ¼¯³É} ÒÔ¼°\citetitle[../api/api.html]{Python/C API ²Î¿¼ÊÖ²á}¡£Õ⼸±¾Ê麸ÇÁ˸÷¸öÉî¶ÈÉϵÄPython֪ʶ¡£
86
87 This tutorial does not attempt to be comprehensive and cover every
88 single feature, or even every commonly used feature. Instead, it
89 introduces many of Python's most noteworthy features, and will give
90 you a good idea of the language's flavor and style. After reading it,
91 you will be able to read and write Python modules and programs, and
92 you will be ready to learn more about the various Python library
93 modules described in the \citetitle[../lib/lib.html]{Python Library
94 Reference}.
95
96 ±¾Êֲ᲻»áº¸Ç Python
97 µÄËùÓй¦ÄÜ£¬Ò²²»»áÈ¥½âÊÍËùÓõ½µÄËùÓÐÏà¹ØµÄ֪ʶ¡£Ïà·´£¬Ëü½éÉÜÁËÐí¶à
98 Python
99 ÖÐ×îÒýÈËעĿµÄ¹¦ÄÜ£¬Õâ»á¶Ô¶ÁÕßÕÆÎÕÕâÃÅÓïÑԵķç¸ñ´óÓаïÖú¡£¶Á¹ýËüºó£¬ÄãÓ¦¸Ã¿ÉÒÔÔĶÁºÍ±àд
100 Python Ä£¿éºÍ³ÌÐò£¬½ÓÏÂÀ´¿ÉÒÔ´Ó \citetitle[../lib/lib.html]{Python
101 ¿â²Î¿¼ÊÖ²á} ÖнøÒ»²½Ñ§Ï°Python¸´ÔÓ¶à±äµÄ¿âºÍÄ£¿é¡£
102
103 \end{abstract}
104
105 \tableofcontents
106
107
108 \chapter{Whetting Your Appetite ¿ªÎ¸²Ë \label{intro}}
109
110 If you do much work on computers, eventually you find that there's
111 some task you'd like to automate. For example, you may wish to
112 perform a search-and-replace over a large number of text files, or
113 rename and rearrange a bunch of photo files in a complicated way.
114 Perhaps you'd like to write a small custom database, or a specialized
115 GUI application, or a simple game.
116
117 ¼ÙÉèÈç¹ûÄãÒªÓüÆËã»ú×öºÜ¶à¹¤×÷£¬ÄãÏ£ÍûÓÐЩÈÎÎñ¿ÉÒÔ×Ô¶¯Íê³É¡£ÀýÈ磬Äã¿ÉÄÜÏ£ÍûÔÚ´óÁ¿µÄÎı¾ÎļþÖнøÐвéÕÒÌæ»»²Ù×÷£¬Ò²ÐíÊÇͨ¹ý¸´Ôӵķ½Ê½ÖØÃüÃû²¢ÖØÐ°ڷÅÒ»ÅúͼÏñÎļþ¡£¿ÉÄÜÄãϲ»¶Ð´¸öСµÄ¶¨ÖÆÊý¾Ý¿â£¬»òÕßÌØÊâµÄGUIÓ¦ÓóÌÐò£¬»òÕß¼òµ¥µÄÓÎÏ·¡£
118
119 If you're a professional software developer, you may have to work with
120 several C/\Cpp/Java libraries but find the usual
121 write/compile/test/re-compile cycle is too slow. Perhaps you're
122 writing a test suite for such a library and find writing the testing
123 code a tedious task. Or maybe you've written a program that could use
124 an extension language, and you don't want to design and implement a
125 whole new language for your application.
126
127 Èç¹ûÄãÊǸöרҵµÄÈí¼þ¿ª·¢Õߣ¬Äã¿ÉÄÜÒªÓü¸¸ö C/\Cpp/Java ¿â¹¤×÷£¬µ«ÊÇ·¢ÏÖͨ³£µÄ±àд/±àÒë/²âÊÔ/ÖØ±àÒëÑ»·Ì«ÂýÁË¡£¿ÉÄÜÄãÔÚ¸øÃ¿¸ö¿â±àд¶ÔÓ¦µÄ²âÊÔ´úÂ룬µ«ÊÇ·¢ÏÖÕâÊÇÒ»¸ö·³È˵Ļî¶ù¡£»òÕßÄãÔÚ±àдһ¸ö´øÓÐÀ©Õ¹ÓïÑԵijÌÐò£¬¶øÄã²»Ïë¸øÄãµÄÓ¦ÓóÌÐòÉè¼ÆºÍʵÏÖÒ»ÃÅȫеÄÓïÑÔ¡£
128
129 Python is just the language for you.
130
131 Python ¾ÍÊÇÄãÐèÒªµÄÓïÑÔ¡£
132
133 You could write a {\UNIX} shell script or Windows batch files for some
134 of these tasks, but shell scripts are best at moving around files and
135 changing text data, not well-suited for GUI applications or games.
136 You could write a C/{\Cpp}/Java program, but it can take a lot of
137 development time to get even a first-draft program. Python is simpler
138 to use, available on Windows, MacOS X, and {\UNIX} operating systems,
139 and will help you get the job done more quickly.
140
141 ÄãÄܹ»Õë¶ÔһЩÈÎÎñ±àд {\UNIX} shell ½Å±¾»òÕß Windows Åú´¦ÀíÎļþ£¬µ«Êǽű¾ÓïÑÔ×îÉó¤Òƶ¯ÎļþºÍÐÞ¸ÄÎı¾Êý¾Ý£¬²»ÊÊºÏ GUI Ó¦ÓóÌÐò»òÕßÓÎÏ·¡£ÄãÄÜд C/{\Cpp}/Java³ÌÐò£¬µ«ÊÇÕâЩ¼¼Êõ¾ÍÊÇ¿ª·¢×î¼òµ¥µÄ³ÌÐòÒ²ÒªÓÃÈ¥´óÁ¿µÄ¿ª·¢Ê±¼ä¡£ÎÞÂÛÔÚ Windows¡¢MacOS X »òÕß {\UNIX} ²Ù×÷ϵͳÉÏ£¬Python ·Ç³£Ò×ÓÚʹÓ㬿ÉÒÔ°ïÖúÄã¸ü¿ìµÄÍê³ÉÈÎÎñ¡£
142
143 Python is simple to use, but it is a real programming language,
144 offering much more structure and support for large programs than shell
145 scripts or batch files can offer. On the other hand, Python also
146 offers much more error checking than C, and, being a
147 \emph{very-high-level language}, it has high-level data types built
148 in, such as flexible arrays and dictionaries. Because of its more
149 general data types Python is applicable to a much larger problem
150 domain than Awk or even Perl, yet many things are at
151 least as easy in Python as in those languages.
152
153 Python ºÜÈÝÒ×ÉÏÊÖ£¬µ«ËüÊÇÒ»ÃÅÕæÕýµÄ±à³ÌÓïÑÔ£¬Ïà¶ÔÓÚ Shell£¬ËüÌṩµÄÕë¶Ô´óÐͳÌÐòµÄÖ§³ÖºÍ½á¹¹Òª¶àµÄ¶à¡£ÁíÒ»·½Ã棬ËüÌṩÁË±È C ¸ü¶àµÄ´íÎó¼ì²é£¬²¢ÇÒ£¬×öΪһÃÅ\emph{·Ç³£¸ß¼¶µÄÓïÑÔ}£¬ËüÓµÓÐÄÚÖõĸ߼¶Êý¾ÝÀàÐÍ£¬ÀýÈç¿É±äÊý×éºÍ×ֵ䣬Èç¹ûͨ¹ý C À´ÊµÏֵϰ£¬ÕâЩ¹¤×÷¿ÉÄÜÈÃÄã´ó¸ÉÉϼ¸ÌìµÄʱ¼ä¡£ÒòΪӵÓиü¶àµÄͨÓÃÊý¾ÝÀàÐÍ£¬Python
154 ÊÊºÏ±È \emph{Awk} ÉõÖÁ \emph{Perl} ¸ü¹ã·ºµÄÎÊÌâÁìÓò£¬ÔÚÆäËüµÄºÜ¶àÁìÓò£¬Python ÖÁÉٱȱðµÄÓïÑÔÒªÒ×Óõöࡣ
155
156 Python allows you to split your program into modules that can be
157 reused in other Python programs. It comes with a large collection of
158 standard modules that you can use as the basis of your programs --- or
159 as examples to start learning to program in Python. Some of these
160 modules provide things like file I/O, system calls,
161 sockets, and even interfaces to graphical user interface toolkits like Tk.
162
163 Python ¿ÉÒÔÈÃÄã°Ñ×Ô¼ºµÄ³ÌÐò·Ö¸ô³É²»Í¬µÄÄ£¿é£¬ÒÔ±ãÔÚÆäËüµÄ Python ³ÌÐòÖÐÖØÓá£ÕâÑùÄã¾Í¿ÉÒÔÈÃ×Ô¼ºµÄ³ÌÐò»ùÓÚÒ»¸öºÜ´óµÄ±ê׼ģ¿é¼¯»òÕßÓÃËüÃÇ×öΪʾÀýÀ´Ñ§Ï° Python ±à³Ì¡£Python Öм¯³ÉÁËһЩÀàËÆÎļþ I/O£¬ÏµÍ³µ÷Óã¬sockets£¬ÉõÖÁÏñ Tk ÕâÑùµÄͼÐι¤¾ß½Ó¿Ú¡£
164
165
166 Python is an interpreted language, which can save you considerable time
167 during program development because no compilation and linking is
168 necessary. The interpreter can be used interactively, which makes it
169 easy to experiment with features of the language, to write throw-away
170 programs, or to test functions during bottom-up program development.
171 It is also a handy desk calculator.
172
173 PythonÊÇһÎâÊÍÐÍÓïÑÔ£¬ÒòΪ²»ÐèÒª±àÒëºÍÁ´½ÓµÄʱ¼ä£¬Ëü¿ÉÒÔ°ïÄãÊ¡ÏÂһЩ¿ª·¢Ê±¼ä¡£½âÊÍÆ÷¿ÉÒÔ½»»¥Ê½Ê¹Óã¬ÕâÑù¾Í¿ÉÒԺܷ½±ãµÄ²âÊÔÓïÑÔÖеĸ÷ÖÖ¹¦ÄÜ£¬ÒÔ±ãÓÚ±àд·¢²¼ÓõijÌÐò£¬»òÕß½øÐÐ×Ô϶øÉϵĿª·¢¡£»¹¿ÉÒÔµ±ËüÊÇÒ»¸öËæÊÖ¿ÉÓõļÆËãÆ÷¡£
174
175 Python enables programs to be written compactly and readably. Programs
176 written in Python are typically much shorter than equivalent C,
177 \Cpp{}, or Java programs, for several reasons:
178
179 Python ¿ÉÒÔд³öºÜ½ô´ÕºÍ¿É¶ÁÐÔºÜÇ¿µÄ³ÌÐò¡£Óà Python дµÄ³ÌÐòͨ³£±ÈͬÑùµÄ C¡¢\Cpp{} »òJava³ÌÐòÒª¶ÌµÃ¶à£¬ÕâÊÇÒòΪÒÔϼ¸¸öÔÒò£º
180
181
182 \begin{itemize}
183 \item
184 the high-level data types allow you to express complex operations in a
185 single statement;
186 \item
187 statement grouping is done by indentation instead of beginning and ending
188 brackets;
189 \item
190 no variable or argument declarations are necessary.
191
192 \item ¸ß¼¶Êý¾Ý½á¹¹Ê¹Äã¿ÉÒÔÔÚÒ»¸öµ¥¶ÀµÄÓï¾äÖбí´ï³öºÜ¸´ÔӵIJÙ×÷£»
193 \item Óï¾äµÄ×éÖ¯ÒÀÀµÓÚËõ½ø¶ø²»ÊÇ begin/end ¿é£»
194 \item ²»ÐèÒª±äÁ¿»ò²ÎÊýÉùÃ÷¡£
195
196 \end{itemize}
197
198 Python is \emph{extensible}: if you know how to program in C it is easy
199 to add a new built-in function or module to the interpreter, either to
200 perform critical operations at maximum speed, or to link Python
201 programs to libraries that may only be available in binary form (such
202 as a vendor-specific graphics library). Once you are really hooked,
203 you can link the Python interpreter into an application written in C
204 and use it as an extension or command language for that application.
205
206 Python ÊÇ \emph{¿ÉÀ©Õ¹µÄ}£ºÈç¹ûÄã»áÓà C ÓïÑÔд³ÌÐò£¬ÄǾͿÉÒÔºÜÈÝÒ×µÄΪ½âÊÍÆ÷Ìí¼ÓÐµļ¯³ÉÄ£¿éºÍ¹¦ÄÜ£¬»òÕßÓÅ»¯Æ¿¾±£¬Ê¹Æä´ïµ½×î´óËÙ¶È£¬»òÕßʹ Python Äܹ»Á´½Óµ½ËùÐèµÄ¶þ½øÖƼܹ¹ÉÏ£¨±ÈÈçij¸öרÓõÄÉÌҵͼÐο⣩¡£µÈÄãÕæÕýÊìϤÕâÒ»ÇÐÁË£¬Äã¾Í¿ÉÒÔ½« Python ¼¯³É½øÓÉ C д³ÉµÄ³ÌÐò£¬°Ñ Python µ±×öÕâ¸ö³ÌÐòµÄÀ©Õ¹»òÃüÁîÐÐÓïÑÔ¡£
207
208 By the way, the language is named after the BBC show ``Monty Python's
209 Flying Circus'' and has nothing to do with nasty reptiles. Making
210 references to Monty Python skits in documentation is not only allowed,
211 it is encouraged!
212
213 ˳±ã˵һÏ£¬Õâ¸öÓïÑÔµÄÃû×ÖÀ´Ô´ÓÚ BBC µÄ¡°Monty Python's Flying Circus¡±½ÚÄ¿£¬ºÍÐ×Ã͵ÄÅÀ³æÃ»ÓÐÈκιØÏµ¡£ÔÚÎĵµÖÐÒýÓà Monty Python µä¹Ê²»½öÊÇÔÊÐíµÄ£¬¶øÇÒ»¹Êܵ½¹ÄÀø£¡
214
215 %\section{Where From Here ¸½ÑÔ \label{where}}
216
217 Now that you are all excited about Python, you'll want to examine it
218 in some more detail. Since the best way to learn a language is
219 to use it, the tutorial invites you to play with the Python interpreter
220 as you read.
221
222 ÏÖÔÚÎÒÃÇÒѾÁ˽âÁË Python ÖÐËùÓ줶¯ÈËÐĵĶ«Î÷£¬´ó¸ÅÄãÏë×ÐϸµÄÊÔÊÔËüÁË¡£Ñ§Ï°Ò»ÃÅÓïÑÔ×îºÃµÄ°ì·¨¾ÍÊÇʹÓÃËü£¬ÈçÄãËù¶Áµ½µÄ£¬±¾ÎÄ»áÒýÁìÄãÔËÓà Python ½âÊÍÆ÷¡£
223
224 In the next chapter, the mechanics of using the interpreter are
225 explained. This is rather mundane information, but essential for
226 trying out the examples shown later.
227
228 ÏÂÒ»½ÚÖУ¬ÎÒÃÇÖ±½Ó˵Ã÷½âÊÍÆ÷µÄÓ÷¨¡£ÕâûÓÐʲôÉñÃØµÄÄÚÈÝ£¬²»¹ýÓÐÖúÓÚÎÒÃÇÁ·Ï°ºóÃæÕ¹Ê¾µÄÀý×Ó¡£
229
230
231 The rest of the tutorial introduces various features of the Python
232 language and system through examples, beginning with simple
233 expressions, statements and data types, through functions and modules,
234 and finally touching upon advanced concepts like exceptions
235 and user-defined classes.
236
237 ±¾Ö¸ÄÏÆäËü²¿·Öͨ¹ýÀý×Ó½éÉÜÁË Python ÓïÑÔºÍϵͳµÄ¸÷ÖÖ¹¦ÄÜ£¬¿ªÊ¼ÊǼòµ¥±í´ïʽ¡¢Óï·¨ºÍÊý¾ÝÀàÐÍ£¬½ÓÏÂÀ´ÊǺ¯ÊýºÍÄ£¿é£¬×îºóÊÇÖîÈçÒì³£ºÍ×Ô¶¨ÒåÀàÕâÑùµÄ¸ß¼¶ÄÚÈÝ¡£
238
239
240
241 \chapter{Using the Python Interpreter ʹÓÃPython½âÊÍÆ÷\label{using}}
242
243 \section{Invoking the Interpreter µ÷ÓýâÊÍÆ÷\label{invoking}}
244
245 The Python interpreter is usually installed as
246 \file{/usr/local/bin/python} on those machines where it is available;
247 putting \file{/usr/local/bin} in your \UNIX{} shell's search path
248 makes it possible to start it by typing the command
249
250 ͨ³£ Python µÄ½âÊÍÆ÷±»°²×°ÔÚÄ¿±ê»úÆ÷µÄ \file{/usr/local/bin/python} Ŀ¼Ï£»°Ñ \file{/usr/local/bin} Ŀ¼·Å½øÄãµÄ\UNIX{} Shell µÄËÑË÷·¾¶Àȷ±£Ëü¿ÉÒÔͨ¹ýÊäÈë
251 \begin{verbatim}
252 python
253 \end{verbatim}
254
255 to the shell. Since the choice of the directory where the interpreter
256 lives is an installation option, other places are possible; check with
257 your local Python guru or system administrator. (E.g.,
258 \file{/usr/local/python} is a popular alternative location.)
259
260 À´Æô¶¯¡£ÒòΪ°²×°Â·¾¶ÊÇ¿ÉÑ¡µÄ£¬ËùÒÔÒ²ÓпÉÄܰ²×°ÔÚÆäËüλÖã¬Äã¿ÉÒÔÓë°²×°
261 Python
262 µÄÓû§»òϵͳ¹ÜÀíÔ±ÁªÏµ¡££¨ÀýÈ磬\file{/usr/local/python}¾ÍÊÇÒ»¸öºÜ³£¼ûµÄÑ¡Ôñ£©
263
264 On Windows machines, the Python installation is usually placed in
265 \file{C:\e Python24}, though you can change this when you're running
266 the installer. To add this directory to your path,
267 you can type the following command into the command prompt in a DOS box:
268
269 ÔÚ Windows»úÆ÷ÉÏ£¬Python ͨ³£°²×°ÔÚ \file{C:\e Python25}(ÔÎÄÊÇ24£¬¿ÉÎÒÃÇÕâÆªÃ÷Ã÷ÊÇ2.5µÄtut£¬¿´À´Ô×÷ÕßÔÚÕâÀï´óÒâÁË¡ª¡ªÒëÕß),µ±È»£¬ÎÒÃÇÔÚÔËÐа²×°³ÌÐòµÄʱºò¿ÉÒԸıäËü¡£ÐèÒª°ÑÕâ¸öĿ¼¼ÓÈëµ½ÎÒÃÇµÄ Path Öеϰ£¬¿ÉÒÔÏñÏÂÃæÕâÑùÔÚ DOS ´°ÖÐÊäÈëÃüÁîÐС£
270
271 \begin{verbatim}
272 set path=%path%;C:\python24
273 \end{verbatim}
274
275 Typing an end-of-file character (\kbd{Control-D} on \UNIX,
276 \kbd{Control-Z} on Windows) at the primary prompt causes the
277 interpreter to exit with a zero exit status. If that doesn't work,
278 you can exit the interpreter by typing the following commands:
279 \samp{import sys; sys.exit()}.
280
281 ÊäÈëÒ»¸öÎļþ½áÊø·û£¨\UNIX ÉÏÊÇ\ kbd{Ctrl+D}£¬WindowsÉÏÊÇ \kbd{Ctrl+Z}£©½âÊÍÆ÷»áÒÔ0ÖµÍ˳ö¡£Èç¹ûÕâûÓÐÆð×÷Óã¬Äã¿ÉÒÔÊäÈëÒÔÏÂÃüÁîÍ˳ö£º\samp{import
282 sys; sys.exit()}¡£
283
284 The interpreter's line-editing features usually aren't very
285 sophisticated. On \UNIX, whoever installed the interpreter may have
286 enabled support for the GNU readline library, which adds more
287 elaborate interactive editing and history features. Perhaps the
288 quickest check to see whether command line editing is supported is
289 typing Control-P to the first Python prompt you get. If it beeps, you
290 have command line editing; see Appendix \ref{interacting} for an
291 introduction to the keys. If nothing appears to happen, or if
292 \code{\^P} is echoed, command line editing isn't available; you'll
293 only be able to use backspace to remove characters from the current
294 line.
295
296 ½âÊÍÆ÷µÄÐб༹¦Äܲ¢²»ºÜ¸´ÔÓ¡£×°ÔÚ\UNIX ÉϵĽâÊÍÆ÷¿ÉÄÜ»áÓÐ GNU readline ¿âÖ§³Ö£¬ÕâÑù¾Í¿ÉÒÔ¶îÍâµÃµ½¾«ÇɵĽ»»¥±à¼ºÍÀúÊ·¼Ç¼¹¦ÄÜ¡£¿ÉÄܼì²éÃüÁîÐÐ±à¼Æ÷Ö§³ÖÄÜÁ¦×î·½±ãµÄ·½Ê½ÊÇÔÚÖ÷Ìáʾ·ûÏÂÊäÈëCtrl-P¡£Èç¹ûÓÐà½à½Éù£¨¼ÆËã»úÑïÉùÆ÷£©£¬ËµÃ÷Äã¿ÉÒÔʹÓÃÃüÁîÐб༹¦ÄÜ£¬´Ó¸½Â¼ A \ref{interacting} ¿ÉÒԲ鵽¿ì½Ý¼üµÄ½éÉÜ¡£Èç¹ûʲôҲûÓз¢Éù£¬»òÕß\code{\^P}ÏÔʾÁ˳öÀ´£¬ËµÃ÷ÃüÁîÐб༹¦Äܲ»¿ÉÓã¬ÄãÖ»ÓÐÓÃÍ˸ñ¼üɾµôÊäÈëµÄÃüÁîÁË¡£
297
298 The interpreter operates somewhat like the \UNIX{} shell: when called
299 with standard input connected to a tty device, it reads and executes
300 commands interactively; when called with a file name argument or with
301 a file as standard input, it reads and executes a \emph{script} from
302 that file.
303
304 ½âÊÍÆ÷µÄ²Ù×÷ÓÐЩÏñ \UNIX{} Shell£ºÊ¹ÓÃÖÕ¶ËÉ豸×öΪ±ê×¼ÊäÈëÀ´µ÷ÓÃËüʱ£¬½âÊÍÆ÷½»»¥µÄ½â¶ÁºÍÖ´ÐÐÃüÁͨ¹ýÎļþÃû²ÎÊý»òÒÔÎļþ×öΪ±ê×¼ÊäÈëÉ豸ʱ£¬Ëü´ÓÎļþÖнâ¶Á²¢Ö´ÐÐ\emph{½Å±¾}¡£
305
306 A second way of starting the interpreter is
307 \samp{\program{python} \programopt{-c} \var{command} [arg] ...}, which
308 executes the statement(s) in \var{command}, analogous to the shell's
309 \programopt{-c} option. Since Python statements often contain spaces
310 or other characters that are special to the shell, it is best to quote
311 \var{command} in its entirety with double quotes.
312
313 Æô¶¯½âÊÍÆ÷µÄµÚ¶þ¸ö·½·¨ÊÇ\samp{\program{python} \programopt{-c} \var{command} [arg] ...}£¬ÕâÖÖ·½·¨¿ÉÒÔÔÚÃüÁîÐÐÖÐÖ±½ÓÖ´ÐÐÓï¾ä£¬µÈͬÓÚShellµÄ \programopt{-c} Ñ¡Ïî¡£ÒòΪPythonÓï¾äͨ³£»á°üÀ¨¿Õ¸ñÖ®ÀàµÄÌØÊâ×Ö·û£¬ËùÒÔ×îºÃ°ÑÕû¸ö \var{Óï¾ä} ÓÃË«ÒýºÅ°üÆðÀ´¡£
314
315 Some Python modules are also useful as scripts. These can be invoked using
316 \samp{\program{python} \programopt{-m} \var{module} [arg] ...}, which
317 executes the source file for \var{module} as if you had spelled out its
318 full name on the command line.
319
320 ÓÐЩ Python Ä£¿éÒ²¿ÉÒÔµ±×÷½Å±¾Ê¹Óá£ËüÃÇ¿ÉÒÔÓà \samp{\program{python} \programopt{-m} \var{module} [arg] ...} µ÷Óã¬ÕâÑù¾Í»áÏñÄãÔÚÃüÁîÐÐÖиø³öÆäÍêÕûÃû×ÖÒ»ÑùÔËÐÐÔ´Îļþ¡£
321
322 Note that there is a difference between \samp{python file} and
323 \samp{python <file}. In the latter case, input requests from the
324 program, such as calls to \function{input()} and \function{raw_input()}, are
325 satisfied from \emph{file}. Since this file has already been read
326 until the end by the parser before the program starts executing, the
327 program will encounter end-of-file immediately. In the former case
328 (which is usually what you want) they are satisfied from whatever file
329 or device is connected to standard input of the Python interpreter.
330
331 ×¢Òâ\samp{python file}ºÍ\samp{python <file}ÊÇÓÐÇø±ðµÄ¡£¶ÔÓÚºóÒ»ÖÖÇé¿ö£¬³ÌÐòÖÐÀàËÆÓÚµ÷Óà \function{input()}\function{raw_input()} ÕâÑùµÄÊäÈëÇëÇó£¬À´×ÔÓÚÈ·¶¨µÄ\emph{Îļþ}¡£ÒòΪÔÚ½âÎöÆ÷¿ªÊ¼Ö´ÐÐ֮ǰ£¬ÎļþÒѾÍêÈ«¶ÁÈ룬ËùÒÔ³ÌÐòÖ¸ÏòÎļþβ¡£ÔÚǰһÖÖÇé¿ö£¨Õâͨ³£ÊÇÄãÐèÒªµÄ£©ËüÃÇ´ÓÀ´×ÔÓÚÈκÎÁª½Óµ½ Python ½âÊÍÆ÷µÄ±ê×¼ÊäÈ룬ÎÞÂÛËüÃÇÊÇÎļþ»¹ÊÇÆäËüÉ豸¡£
332
333 When a script file is used, it is sometimes useful to be able to run
334 the script and enter interactive mode afterwards. This can be done by
335 passing \programopt{-i} before the script. (This does not work if the
336 script is read from standard input, for the same reason as explained
337 in the previous paragraph.)
338
339 ʹÓýű¾Îļþʱ£¬¾³£»áÔËÐнű¾È»ºó½øÈë½»»¥Ä£Ê½¡£ÕâÒ²¿ÉÒÔͨ¹ýÔڽű¾Ö®Ç°¼ÓÉÏ \programopt{-i} ²ÎÊýÀ´ÊµÏÖ¡££¨Èç¹û½Å±¾À´×Ô±ê×¼ÊäÈ룬¾Í²»ÄÜÕâÑùÔËÐУ¬Óëǰһ¶ÎÌáµ½µÄÔÒòÒ»Ñù¡££©
340
341 \subsection{Argument Passing ²ÎÊý´«µÝ \label{argPassing}}
342
343 When known to the interpreter, the script name and additional
344 arguments thereafter are passed to the script in the variable
345 \code{sys.argv}, which is a list of strings. Its length is at least
346 one; when no script and no arguments are given, \code{sys.argv[0]} is
347 an empty string. When the script name is given as \code{'-'} (meaning
348 standard input), \code{sys.argv[0]} is set to \code{'-'}. When
349 \programopt{-c} \var{command} is used, \code{sys.argv[0]} is set to
350 \code{'-c'}. When \programopt{-m} \var{module} is used, \code{sys.argv[0]}
351 is set to the full name of the located module. Options found after
352 \programopt{-c} \var{command} or \programopt{-m} \var{module} are not consumed
353 by the Python interpreter's option processing but left in \code{sys.argv} for
354 the command or module to handle.
355
356 µ÷ÓýâÊÍÆ÷ʱ£¬½Å±¾ÃûºÍ¸½¼Ó²ÎÊý´«ÈëÒ»¸öÃûΪ \code{sys.argv} µÄ×Ö·û´®ÁÐ±í¡£Ã»Óиø¶¨½Å±¾ºÍ²ÎÊýʱ£¬ËüÖÁÉÙÒ²ÓÐÒ»¸öÔªËØ£º\code{sys.argv[0]} ´ËʱΪ¿Õ×Ö·û´®¡£½Å±¾ÃûÖ¸¶¨Îª \code{'-'} £¨±íʾ±ê×¼ÊäÈ룩ʱ£¬ \code{sys.argv[0]}±»É趨Ϊ\code{'-'}£¬Ê¹ÓÃ
357 \programopt{-c} \var{Ö¸Áî} ʱ£¬ \code{sys.argv[0]} ±»É趨Ϊ\code{'-c'}¡£ ʹÓÃ\programopt{-m} \var{module}²ÎÊýʱ£¬\code{sys.agv[0]} ±»É趨Ϊָ¶¨Ä£¿éµÄÈ«Ãû¡£\programopt{-c} \var{command} »òÕß \programopt{-m} \var{module} Ö®ºóµÄ²ÎÊý²»»á±»
358 Python ½âÊÍÆ÷µÄÑ¡Ïî´¦Àí»úÖÆËù½Ø»ñ£¬¶øÊÇÁôÔÚ\code{sys.argv} ÖУ¬¹©½Å±¾ÃüÁî²Ù×÷¡£
359
360 \subsection{Interactive Mode ½»»¥Ä£Ê½\label{interactive}}
361
362 When commands are read from a tty, the interpreter is said to be in
363 \emph{interactive mode}. In this mode it prompts for the next command
364 with the \emph{primary prompt}, usually three greater-than signs
365 (\samp{>>>~}); for continuation lines it prompts with the
366 \emph{secondary prompt}, by default three dots (\samp{...~}).
367 The interpreter prints a welcome message stating its version number
368 and a copyright notice before printing the first prompt:
369
370 ´Ó tty ¶ÁÈ¡ÃüÁîʱ£¬ÎÒÃdzƽâÊÍÆ÷¹¤×÷ÓÚ\emph{½»»¥Ä£Ê½} ¡£ÕâÖÖģʽÏÂËü¸ù¾Ý\emph{Ö÷Ìáʾ·û}À´Ö´ÐУ¬Ö÷Ìáʾ·ûͨ³£±êʶΪÈý¸ö´óÓںţ¨ \samp{>>>~} £©£»¼ÌÐøµÄ²¿·Ö±»³ÆÎª \emph{´ÓÊôÌáʾ·û} £¬ÓÉÈý¸öµã±êʶ£¨\samp{...~}£©¡£ÔÚµÚÒ»ÐÐ֮ǰ£¬½âÊÍÆ÷´òÓ¡»¶ÓÐÅÏ¢¡¢°æ±¾ºÅºÍÊÚȨÌáʾ£º
371
372 \begin{verbatim}
373 python
374 Python 1.5.2b2 (#1, Feb 28 1999, 00:02:06) [GCC 2.8.1] on sunos5
375 Copyright 1991-1995 Stichting Mathematisch Centrum, Amsterdam
376 >>>
377 \end{verbatim}
378
379 Continuation lines are needed when entering a multi-line construct.
380 As an example, take a look at this \keyword{if} statement:
381
382 ÊäÈë¶àÐнṹʱÐèÒª´ÓÊôÌáʾ·ûÁË£¬ÀýÈ磬ÏÂÃæÕâ¸ö \keyword{if} Óï¾ä£º
383
384
385 \begin{verbatim}
386 >>> the_world_is_flat = 1
387 >>> if the_world_is_flat:
388 ... print "Be careful not to fall off!"
389 ...
390 Be careful not to fall off!
391 \end{verbatim}
392
393
394 \section{The Interpreter and Its Environment ½âÊÍÆ÷¼°Æä»·¾³\label{interp}}
395
396 \subsection{Error Handling ´íÎó´¦Àí\label{error}}
397
398 When an error occurs, the interpreter prints an error
399 message and a stack trace. In interactive mode, it then returns to
400 the primary prompt; when input came from a file, it exits with a
401 nonzero exit status after printing
402 the stack trace. (Exceptions handled by an \keyword{except} clause in a
403 \keyword{try} statement are not errors in this context.) Some errors are
404 unconditionally fatal and cause an exit with a nonzero exit; this
405 applies to internal inconsistencies and some cases of running out of
406 memory. All error messages are written to the standard error stream;
407 normal output from executed commands is written to standard
408 output.
409
410 ÓдíÎó·¢Éúʱ£¬½âÊÍÆ÷´òÓ¡Ò»¸ö´íÎóÐÅÏ¢ºÍÕ»¸ú×ÙÆ÷¡£½»»¥Ä£Ê½Ï£¬Ëü·µ»ØÖ÷Ìáʾ·û£¬Èç¹û´ÓÎļþÊäÈëÖ´ÐУ¬ËüÔÚ´òÓ¡Õ»¸ú×ÙÆ÷ºóÒÔ·ÇÁã״̬Í˳ö¡££¨Òì³£¿ÉÒÔÓÉ \keyword{try} Óï¾äÖÐµÄ \keyword{except} ×Ó¾äÀ´¿ØÖÆ£¬ÕâÑù¾Í²»»á³öÏÖÉÏÎÄÖеĴíÎóÐÅÏ¢£©ÓÐһЩ·Ç³£ÖÂÃüµÄ´íÎó»áµ¼Ö·ÇÁã״̬ÏÂÍ˳ö£¬ÕâÓÉͨ³£ÓÉÄÚ²¿Ã¬¶ÜºÍÄÚ´æÒç³öÔì³É¡£ËùÓеĴíÎóÐÅÏ¢¶¼Ð´Èë±ê×¼´íÎóÁ÷£»ÃüÁîÖÐÖ´ÐÐµÄÆÕͨÊä³öдÈë±ê×¼Êä³ö¡£
411
412 Typing the interrupt character (usually Control-C or DEL) to the
413 primary or secondary prompt cancels the input and returns to the
414 primary prompt.\footnote{
415 A problem with the GNU Readline package may prevent this.
416 }
417 Typing an interrupt while a command is executing raises the
418 \exception{KeyboardInterrupt} exception, which may be handled by a
419 \keyword{try} statement.
420
421 ÔÚÖ÷Ìáʾ·û»ò¸½ÊôÌáʾ·ûÊäÈëÖжϷû£¨Í¨³£ÊÇControl-C »òÕß DEL£©¾Í»áÈ¡Ïûµ±Ç°ÊäÈ룬»Øµ½Ö÷ÃüÁîÐС£ \footnote{GNU readline °üµÄÒ»¸öÎÊÌâ¿ÉÄÜ»áÔì³ÉËüÎÞ·¨Õý³£¹¤×÷¡£}.Ö´ÐÐÃüÁîʱÊäÈëÒ»¸öÖжϷû»áÅ׳öÒ»¸ö \exception{KeyboardInterrupt} Òì³££¬Ëü¿ÉÒÔ±» \keyword{try} ¾ä½Ø»ñ¡£
422
423
424 \subsection{Executable Python Scripts Ö´ÐÐPython½Å±¾\label{scripts}}
425
426 On BSD'ish \UNIX{} systems, Python scripts can be made directly
427 executable, like shell scripts, by putting the line
428
429 BSDÀàµÄ \UNIX{}ϵͳÖУ¬Python ½Å±¾¿ÉÒÔÏñ Shell
430 ½Å±¾ÄÇÑùÖ±½ÓÖ´ÐС£Ö»ÒªÔڽű¾Îļþ¿ªÍ·Ð´Ò»ÐÐÃüÁָ¶¨ÎļþºÍģʽ£º
431
432 \begin{verbatim}
433 #! /usr/bin/env python
434 \end{verbatim}
435
436 (assuming that the interpreter is on the user's \envvar{PATH}) at the
437 beginning of the script and giving the file an executable mode. The
438 \samp{\#!} must be the first two characters of the file. On some
439 platforms, this first line must end with a \UNIX-style line ending
440 (\character{\e n}), not a Mac OS (\character{\e r}) or Windows
441 (\character{\e r\e n}) line ending. Note that
442 the hash, or pound, character, \character{\#}, is used to start a
443 comment in Python.
444
445 (ҪȷÈÏ Python ½âÊÍÆ÷ÔÚÓû§Â·¾¶ÖÐ) \samp{\#!} ±ØÐëÊÇÎļþµÄǰÁ½¸ö×Ö·û£¬ÔÚijЩƽ̨ÉÏ£¬µÚÒ»ÐбØÐëÒÔ \UNIX ·ç¸ñµÄÐнáÊø·û£¨\character{\e n}£©½áÊø£¬²»ÄÜÓÃMac£¨\character{\e r}£©»òWindows£¨\character{\e r\e n}£©µÄ½áÊø·û¡£×¢Ò⣬\character{\#}ÊÇPythonÖÐÊÇÐÐ×¢ÊÍµÄÆðʼ·û¡£
446
447 The script can be given an executable mode, or permission, using the
448 \program{chmod} command:
449
450 ½Å±¾¿ÉÒÔͨ¹ý \program{chmod} ÃüÁîÖ¸¶¨Ö´ÐÐģʽºÍȨÏÞ¡£
451
452 \begin{verbatim}
453 $ chmod +x myscript.py
454 \end{verbatim} % $ <-- bow to font-lock
455
456
457 \subsection{Source Code Encoding Ô´³ÌÐò±àÂë}
458
459 It is possible to use encodings different than \ASCII{} in Python source
460 files. The best way to do it is to put one more special comment line
461 right after the \code{\#!} line to define the source file encoding:
462
463 Python µÄÔ´Îļþ¿ÉÒÔͨ¹ý±àÂëʹÓà ASCII ÒÔÍâµÄ×Ö·û¼¯¡£×îºÃµÄ×ö·¨ÊÇÔÚ \code{\#!} ÐкóÃæÓÃÒ»¸öÌØÊâµÄ×¢ÊÍÐÐÀ´¶¨Òå×Ö·û¼¯¡£
464
465 \begin{alltt}
466 # -*- coding: \var{encoding} -*-
467 \end{alltt}
468
469 With that declaration, all characters in the source file will be treated as
470 having the encoding \var{encoding}, and it will be
471 possible to directly write Unicode string literals in the selected
472 encoding. The list of possible encodings can be found in the
473 \citetitle[../lib/lib.html]{Python Library Reference}, in the section
474 on \ulink{\module{codecs}}{../lib/module-codecs.html}.
475
476 ¸ù¾ÝÕâ¸öÉùÃ÷£¬Python »á³¢ÊÔ½«ÎļþÖеÄ×Ö·û±àÂëתΪ \var{encoding} ±àÂë¡£²¢ÇÒ£¬Ëü¾¡¿ÉÄܵĽ«Ö¸¶¨µÄ±àÂëÖ±½Óд³É Unicode Îı¾¡£ÔÚ \citetitle[../lib/lib.html]{Python ¿â²Î¿¼ÊÖ²á} ÖÐ \ulink{\module{codecs}}{../lib/module-codecs.html} ²¿·Ý¿ÉÒÔÕÒµ½¿ÉÓõıàÂëÁÐ±í£¨¸ù¾Ý¸öÈ˾Ñé£¬ÍÆ¼öʹÓà cp-936»òutf-8´¦ÀíÖÐÎÄ££ÒëÕß×¢£©¡£
477
478 For example, to write Unicode literals including the Euro currency
479 symbol, the ISO-8859-15 encoding can be used, with the Euro symbol
480 having the ordinal value 164. This script will print the value 8364
481 (the Unicode codepoint corresponding to the Euro symbol) and then
482 exit:
483
484 ÀýÈ磬¿ÉÒÔÓà ISO-8859-15 ±àÂë¿ÉÒÔÓÃÀ´±àд°üº¬Å·Ôª·ûºÅµÄ Unicode Îı¾£¬Æä±àÂëֵΪ 164¡£Õâ¸ö½Å±¾»áÊä³ö 8364 £¨Å·Ôª·ûºÅµÄ Unicode ¶ÔÓ¦±àÂ룩ȻºóÍ˳ö£º
485
486 \begin{alltt}
487 # -*- coding: iso-8859-15 -*-
488
489 currency = u"\texteuro"
490 print ord(currency)
491 \end{alltt}
492
493 If your editor supports saving files as \code{UTF-8} with a UTF-8
494 \emph{byte order mark} (aka BOM), you can use that instead of an
495 encoding declaration. IDLE supports this capability if
496 \code{Options/General/Default Source Encoding/UTF-8} is set. Notice
497 that this signature is not understood in older Python releases (2.2
498 and earlier), and also not understood by the operating system for
499 script files with \code{\#!} lines (only used on \UNIX{} systems).
500
501 Èç¹ûÄãµÄÎļþ±à¼Æ÷Ö§³Ö \code{UTF-8} ¸ñʽ£¬²¢ÇÒ¿ÉÒÔ±£´æ \code{UTF-8} ±ê¼Ç£¨\emph{aka BOM - Byte Order Mark}£©£¬Äã¿ÉÒÔÓÃÕâ¸öÀ´´úÌæ±àÂëÉùÃ÷¡£IDLE¿ÉÒÔͨ¹ýÉ趨\code{Options/General/Default Source Encoding/UTF-8} À´Ö§³ÖËü¡£ÐèҪעÒâµÄÊǾɰæPython²»Ö§³ÖÕâ¸ö±ê¼Ç£¨Python 2.2»ò¸üÔçµÄ°æ±¾£©£¬Í¬ÑùÖ§³Ö\code{\#!}ÐеIJÙ×÷ϵͳҲ²»»áÖ§³ÖËü£¨½öÓÃÓÚ \UNIX{}ϵͳ£©¡£
502
503 By using UTF-8 (either through the signature or an encoding
504 declaration), characters of most languages in the world can be used
505 simultaneously in string literals and comments. Using non-\ASCII{}
506 characters in identifiers is not supported. To display all these
507 characters properly, your editor must recognize that the file is
508 UTF-8, and it must use a font that supports all the characters in the
509 file.
510
511 ʹÓà UTF-8 ÄÚÂ루ÎÞÂÛÊÇÓñê¼Ç»¹ÊDZàÂëÉùÃ÷£©£¬ÎÒÃÇ¿ÉÒÔÔÚ×Ö·û´®ºÍ×¢ÊÍÖÐʹÓÃÊÀ½çÉϵĴ󲿷ÖÓïÑÔ¡£±êʶ·ûÖв»ÄÜʹÓÃ·Ç \ASCII{} ×Ö·û¼¯¡£ÎªÁËÕýÈ·ÏÔʾËùÓеÄ×Ö·û£¬ÄãÒ»¶¨ÒªÔÚ±à¼Æ÷Öн«Îļþ±£´æÎª UTF-8 ¸ñʽ£¬¶øÇÒҪʹÓÃÖ§³ÖÎļþÖÐËùÓÐ×Ö·ûµÄ×ÖÌå¡£
512
513 \subsection{The Interactive Startup File ½»»¥Ê½»·¾³µÄÆô¶¯Îļþ\label{startup}}
514
515 % XXX This should probably be dumped in an appendix, since most people
516 % don't use Python interactively in non-trivial ways.
517
518 When you use Python interactively, it is frequently handy to have some
519 standard commands executed every time the interpreter is started. You
520 can do this by setting an environment variable named
521 \envvar{PYTHONSTARTUP} to the name of a file containing your start-up
522 commands. This is similar to the \file{.profile} feature of the
523 \UNIX{} shells.
524
525 ʹÓà Python ½âÊÍÆ÷µÄʱºò£¬ÎÒÃÇ¿ÉÄÜÐèÒªÔÚÿ´Î½âÊÍÆ÷Æô¶¯Ê±Ö´ÐÐһЩÃüÁî¡£Äã¿ÉÒÔÔÚÒ»¸öÎļþÖаüº¬ÄãÏëÒªÖ´ÐеÄÃüÁÉ趨һ¸öÃûΪ \envvar{PYTHONSTARTUP} µÄ»·¾³±äÁ¿À´Ö¸¶¨Õâ¸öÎļþ¡£ÕâÀàËÆÓÚ Unix shellµÄ \file{.profile} Îļþ¡£
526
527 This file is only read in interactive sessions, not when Python reads
528 commands from a script, and not when \file{/dev/tty} is given as the
529 explicit source of commands (which otherwise behaves like an
530 interactive session). It is executed in the same namespace where
531 interactive commands are executed, so that objects that it defines or
532 imports can be used without qualification in the interactive session.
533 You can also change the prompts \code{sys.ps1} and \code{sys.ps2} in
534 this file.
535
536 Õâ¸öÎļþÔÚ½»»¥»á»°ÆÚÊÇÖ»¶ÁµÄ£¬µ± Python ´Ó½Å±¾Öнâ¶ÁÎļþ»òÒÔÖÕ¶Ë \file{/dev/tty}
537 ×öΪÍⲿÃüÁîԴʱÔò²»»áÈç´Ë£¨¾¡¹ÜËüÃǵÄÐÐΪºÜÏñÊÇ´¦ÔÚ½»»¥»á»°ÆÚ¡££©ËüÓë½âÊÍÆ÷Ö´ÐеÄÃüÁî´¦ÔÚͬһ¸öÃüÃû¿Õ¼ä£¬ËùÒÔÓÉËü¶¨Òå»òÒýÓõÄÒ»ÇпÉÒÔÔÚ½âÊÍÆ÷Öв»ÊÜÏÞÖÆµÄʹÓá£ÄãÒ²¿ÉÒÔÔÚÕâ¸öÎļþÖиıä \code{sys.ps1} ºÍ \code{sys.ps2} Ö¸Áî¡£
538
539 If you want to read an additional start-up file from the current
540 directory, you can program this in the global start-up file using code
541 like \samp{if os.path.isfile('.pythonrc.py'):
542 execfile('.pythonrc.py')}. If you want to use the startup file in a
543 script, you must do this explicitly in the script:
544
545 Èç¹ûÄãÏëÒªÔÚµ±Ç°Ä¿Â¼ÖÐÖ´Ðи½¼ÓµÄÆô¶¯Îļþ£¬¿ÉÒÔÔÚÈ«¾ÖÆô¶¯ÎļþÖмÓÈëÀàËÆÒÔϵĴúÂ룺\samp{if os.path.isfile('.pythonrc.py'): execfile('.pythonrc.py')}¡£Èç¹ûÄãÏëÒªÔÚij¸ö½Å±¾ÖÐʹÓÃÆô¶¯Îļþ£¬±ØÐëÒªÔڽű¾ÖÐдÈëÕâÑùµÄÓï¾ä£º
546
547 \begin{verbatim}
548 import os
549 filename = os.environ.get('PYTHONSTARTUP')
550 if filename and os.path.isfile(filename):
551 execfile(filename)
552 \end{verbatim}
553
554
555
556 \chapter{More Control Flow Tools ÉîÈëÁ÷³Ì¿ØÖÆ\label{moreControl}}
557
558 Besides the \keyword{while} statement just introduced, Python knows
559 the usual control flow statements known from other languages, with
560 some twists.
561
562 ³ýÁËÇ°Ãæ½éÉÜµÄ \keyword{while} Óï¾ä£¬Python »¹´Ó±ðµÄÓïÑÔÖÐ½è¼øÁËһЩÁ÷³Ì¿ØÖƹ¦ÄÜ£¬²¢ÓÐËù¸Ä±ä¡£
563
564 \section{\keyword{if} Statements \label{if}}
565
566 Perhaps the most well-known statement type is the
567 \keyword{if} statement. For example:
568
569 Ò²Ðí×îÓÐÃûµÄÊÇ if Óï¾ä¡£ÀýÈ磺
570
571 \begin{verbatim}
572 >>> x = int(raw_input("Please enter an integer: "))
573 >>> if x < 0:
574 ... x = 0
575 ... print 'Negative changed to zero'
576 ... elif x == 0:
577 ... print 'Zero'
578 ... elif x == 1:
579 ... print 'Single'
580 ... else:
581 ... print 'More'
582 ...
583 \end{verbatim}
584
585 There can be zero or more \keyword{elif} parts, and the
586 \keyword{else} part is optional. The keyword `\keyword{elif}' is
587 short for `else if', and is useful to avoid excessive indentation. An
588 \keyword{if} \ldots\ \keyword{elif} \ldots\ \keyword{elif} \ldots\ sequence
589 % Weird spacings happen here if the wrapping of the source text
590 % gets changed in the wrong way.
591 is a substitute for the \keyword{switch} or
592 \keyword{case} statements found in other languages.
593
594 ¿ÉÄÜ»áÓÐÁãµ½¶à¸ö \keyword{elif} ²¿·Ö£¬\keyword{else} ÊÇ¿ÉÑ¡µÄ¡£¹Ø¼ü×Ö¡°\keyword{elif}¡± ÊÇ¡° else if ¡±µÄËõд£¬Õâ¸ö¿ÉÒÔÓÐЧ±ÜÃâ¹ýÉîµÄËõ½ø¡£if ... elif ... elif ... ÐòÁÐÓÃÓÚÌæ´úÆäËüÓïÑÔÖÐµÄ switch »ò case Óï¾ä¡£
595
596 \section{\keyword{for} Statements \keyword{for} Óï¾ä \label{for}}
597
598 The \keyword{for}\stindex{for} statement in Python differs a bit from
599 what you may be used to in C or Pascal. Rather than always
600 iterating over an arithmetic progression of numbers (like in Pascal),
601 or giving the user the ability to define both the iteration step and
602 halting condition (as C), Python's
603 \keyword{for}\stindex{for} statement iterates over the items of any
604 sequence (a list or a string), in the order that they appear in
605 the sequence. For example (no pun intended):
606 % One suggestion was to give a real C example here, but that may only
607 % serve to confuse non-C programmers.
608
609 Python ÖÐµÄ \keyword{for}\stindex{for} Óï¾äºÍ C »ò Pascal ÖеÄÂÔÓв»Í¬¡£Í¨³£µÄÑ»·¿ÉÄÜ»áÒÀ¾ÝÒ»¸öµÈ²îÊýÖµ²½½ø¹ý³Ì£¨ÈçPascal£©»òÓÉÓû§À´¶¨Òåµü´ú²½ÖèºÍÖÐÖ¹Ìõ¼þ£¨Èç C £©£¬Python µÄ \keyword{for}\stindex{for} Óï¾äÒÀ¾ÝÈÎÒâÐòÁУ¨Á´±í»ò×Ö·û´®£©ÖеÄ×ÓÏ°´ËüÃÇÔÚÐòÁÐÖеÄ˳ÐòÀ´½øÐеü´ú¡£ÀýÈ磨ûÓаµÖ¸£©£º
610
611 \begin{verbatim}
612 >>> # Measure some strings:
613 ... a = ['cat', 'window', 'defenestrate']
614 >>> for x in a:
615 ... print x, len(x)
616 ...
617 cat 3
618 window 6
619 defenestrate 12
620 \end{verbatim}
621
622 It is not safe to modify the sequence being iterated over in the loop
623 (this can only happen for mutable sequence types, such as lists). If
624 you need to modify the list you are iterating over (for example, to
625 duplicate selected items) you must iterate over a copy. The slice
626 notation makes this particularly convenient:
627
628 ÔÚµü´ú¹ý³ÌÖÐÐ޸ĵü´úÐòÁв»°²È«£¨Ö»ÓÐÔÚʹÓÃÁ´±íÕâÑùµÄ¿É±äÐòÁÐʱ²Å»áÓÐÕâÑùµÄÇé¿ö£©¡£Èç¹ûÄãÏëÒªÐÞ¸ÄÄãµü´úµÄÐòÁУ¨ÀýÈ磬¸´ÖÆÑ¡ÔñÏ£¬Äã¿ÉÒÔµü´úËüµÄ¸´±¾¡£Ê¹ÓÃÇиî±êʶ¾Í¿ÉÒԺܷ½±ãµÄ×öµ½ÕâÒ»µã£º
629
630 \begin{verbatim}
631 >>> for x in a[:]: # make a slice copy of the entire list
632 ... if len(x) > 6: a.insert(0, x)
633 ...
634 >>> a
635 ['defenestrate', 'cat', 'window', 'defenestrate']
636 \end{verbatim}
637
638
639 \section{The \function{range()} Function \function{range()}º¯Êý \label{range}}
640
641 If you do need to iterate over a sequence of numbers, the built-in
642 function \function{range()} comes in handy. It generates lists
643 containing arithmetic progressions:
644
645 Èç¹ûÄãÐèÒªÒ»¸öÊýÖµÐòÁУ¬ÄÚÖú¯Êýrange()¿ÉÄÜ»áºÜÓÐÓã¬ËüÉú³ÉÒ»¸öµÈ²î¼¶ÊýÁ´±í¡£
646
647 \begin{verbatim}
648 >>> range(10)
649 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
650 \end{verbatim}
651
652 The given end point is never part of the generated list;
653 \code{range(10)} generates a list of 10 values, the legal
654 indices for items of a sequence of length 10. It is possible to let
655 the range start at another number, or to specify a different increment
656 (even negative; sometimes this is called the `step'):
657
658 \code{range(10)} Éú³ÉÁËÒ»¸ö°üº¬10¸öÖµµÄÁ´±í£¬ËüÓÃÁ´±íµÄË÷ÒýÖµÌî³äÁËÕâ¸ö³¤¶ÈΪ10µÄÁÐ±í£¬ËùÉú³ÉµÄÁ´±íÖв»°üÀ¨·¶Î§ÖеĽáÊøÖµ¡£Ò²¿ÉÒÔÈÃrange²Ù×÷´ÓÁíÒ»¸öÊýÖµ¿ªÊ¼£¬»òÕß¿ÉÒÔÖ¸¶¨Ò»¸ö²»Í¬µÄ²½½øÖµ£¨ÉõÖÁÊǸºÊý£¬ÓÐʱÕâÒ²±»³ÆÎª¡°²½³¤¡±£©£º
659
660 \begin{verbatim}
661 >>> range(5, 10)
662 [5, 6, 7, 8, 9]
663 >>> range(0, 10, 3)
664 [0, 3, 6, 9]
665 >>> range(-10, -100, -30)
666 [-10, -40, -70]
667 \end{verbatim}
668
669 To iterate over the indices of a sequence, combine
670 \function{range()} and \function{len()} as follows:
671
672 ÐèÒªµü´úÁ´±íË÷ÒýµÄ»°£¬ÈçÏÂËùʾ½áºÏʹ ÓÃ\function{range()} ºÍ \function{len()} £º
673
674 \begin{verbatim}
675 >>> a = ['Mary', 'had', 'a', 'little', 'lamb']
676 >>> for i in range(len(a)):
677 ... print i, a[i]
678 ...
679 0 Mary
680 1 had
681 2 a
682 3 little
683 4 lamb
684 \end{verbatim}
685
686
687 \section{\keyword{break} and \keyword{continue} Statements, and
688 \keyword{else} Clauses on Loops
689 \label{break}
690 \keyword{break} ºÍ \keyword{continue} Óï¾ä, ÒÔ¼°
691 Ñ»·ÖÐµÄ \keyword{else} ×Ó¾ä}
692
693 The \keyword{break} statement, like in C, breaks out of the smallest
694 enclosing \keyword{for} or \keyword{while} loop.
695
696 break Óï¾äºÍ C ÖеÄÀàËÆ£¬ÓÃÓÚÌø³ö×î½üµÄÒ»¼¶ \keyword{for} »ò \keyword{while} Ñ»·¡£
697
698 The \keyword{continue} statement, also borrowed from C, continues
699 with the next iteration of the loop.
700
701 \keyword{continue} Óï¾äÊÇ´Ó C ÖÐ½è¼øÀ´µÄ£¬Ëü±íʾѻ·¼ÌÐøÖ´ÐÐÏÂÒ»´Îµü´ú¡£
702
703 Loop statements may have an \code{else} clause; it is executed when
704 the loop terminates through exhaustion of the list (with
705 \keyword{for}) or when the condition becomes false (with
706 \keyword{while}), but not when the loop is terminated by a
707 \keyword{break} statement. This is exemplified by the following loop,
708 which searches for prime numbers:
709
710 Ñ»·¿ÉÒÔÓÐÒ»¸ö \code{else} ×Ó¾ä;ËüÔÚÑ»·µü´úÍêÕû¸öÁÐ±í£¨¶ÔÓÚ \keyword{for} £©»òÖ´ÐÐÌõ¼þΪ false £¨¶ÔÓÚ \keyword{while} £©Ê±Ö´ÐУ¬µ«Ñ»·±» \keyword{break} ÖÐÖ¹µÄÇé¿öϲ»»áÖ´ÐС£ÒÔÏÂËÑË÷ËØÊýµÄʾÀý³ÌÐòÑÝʾÁËÕâ¸ö×Ӿ䣺
711
712 \begin{verbatim}
713 >>> for n in range(2, 10):
714 ... for x in range(2, n):
715 ... if n % x == 0:
716 ... print n, 'equals', x, '*', n/x
717 ... break
718 ... else:
719 ... # loop fell through without finding a factor
720 ... print n, 'is a prime number'
721 ...
722 2 is a prime number
723 3 is a prime number
724 4 equals 2 * 2
725 5 is a prime number
726 6 equals 2 * 3
727 7 is a prime number
728 8 equals 2 * 4
729 9 equals 3 * 3
730 \end{verbatim}
731
732
733 \section{\keyword{pass} Statements \keyword{pass} Óï¾ä \label{pass}}
734
735 The \keyword{pass} statement does nothing.
736 It can be used when a statement is required syntactically but the
737 program requires no action.
738 For example:
739
740 \keyword{pass} Óï¾äʲôҲ²»×ö¡£ËüÓÃÓÚÄÇЩÓï·¨ÉϱØÐëÒªÓÐʲôÓï¾ä£¬µ«³ÌÐòʲôҲ²»×öµÄ³¡ºÏ£¬ÀýÈ磺
741
742 \begin{verbatim}
743 >>> while True:
744 ... pass # Busy-wait for keyboard interrupt
745 ...
746 \end{verbatim}
747
748
749 \section{Defining Functions ¶¨Ò庯Êý \label{functions}}
750
751 We can create a function that writes the Fibonacci series to an
752 arbitrary boundary:
753
754 ÎÒÃÇ¿ÉÒÔ¶¨ÒåÒ»¸öº¯ÊýÒÔÉú³ÉÈÎÒâÉϽçµÄ·Æ²¨ÄÇÆõÊýÁУº
755
756 \begin{verbatim}
757 >>> def fib(n): # write Fibonacci series up to n
758 ... """Print a Fibonacci series up to n."""
759 ... a, b = 0, 1
760 ... while b < n:
761 ... print b,
762 ... a, b = b, a+b
763 ...
764 >>> # Now call the function we just defined:
765 ... fib(2000)
766 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597
767 \end{verbatim}
768
769 The keyword \keyword{def} introduces a function \emph{definition}. It
770 must be followed by the function name and the parenthesized list of
771 formal parameters. The statements that form the body of the function
772 start at the next line, and must be indented. The first statement of
773 the function body can optionally be a string literal; this string
774 literal is the function's \index{documentation strings}documentation
775 string, or \dfn{docstring}.\index{docstrings}\index{strings, documentation}
776
777 ¹Ø¼ü×Ö \keyword{def} ÒýÈëÁËÒ»¸öº¯Êý¶¨Òå¡£ÔÚÆäºó±ØÐë¸úÓк¯ÊýÃûºÍ°üÀ¨ÐÎʽ²ÎÊýµÄÔ²À¨ºÅ¡£º¯ÊýÌåÓï¾ä´ÓÏÂÒ»ÐпªÊ¼£¬±ØÐëÊÇËõ½øµÄ¡£º¯ÊýÌåµÄµÚÒ»ÐпÉÒÔÊÇÒ»¸ö×Ö·û´®Öµ£¬Õâ¸ö×Ö·û´®ÊǸú¯ÊýµÄ \dfn(Îĵµ×Ö·û´®£¨documentation string£©)\index{documentation strings}£¬Ò²¿É³Æ×÷ \dfn{docstring}¡£\index{docstrings}\index{strings, documentation}
778
779 There are tools which use docstrings to automatically produce online
780 or printed documentation, or to let the user interactively browse
781 through code; it's good practice to include docstrings in code that
782 you write, so try to make a habit of it.
783
784 ÓÐЩÎĵµ×Ö·û´®¹¤¾ß¿ÉÒÔÔÚÏß´¦Àí»ò´òÓ¡Îĵµ£¬»òÈÃÓû§½»»¥µÄä¯ÀÀ´úÂë;ÔÚ´úÂëÖмÓÈëÎĵµ×Ö·û´®ÊÇÒ»¸öºÃµÄ×÷·¨£¬Ó¦¸ÃÑø³ÉÕâ¸öϰ¹ß¡£
785
786 The \emph{execution} of a function introduces a new symbol table used
787 for the local variables of the function. More precisely, all variable
788 assignments in a function store the value in the local symbol table;
789 whereas variable references first look in the local symbol table, then
790 in the global symbol table, and then in the table of built-in names.
791 Thus, global variables cannot be directly assigned a value within a
792 function (unless named in a \keyword{global} statement), although
793 they may be referenced.
794
795 \emph{Ö´ÐÐ}º¯Êýʱ»áΪ¾Ö²¿±äÁ¿ÒýÈëÒ»¸öеķûºÅ±í¡£ËùÓеľֲ¿±äÁ¿¶¼´æ´¢ÔÚÕâ¸ö¾Ö²¿·ûºÅ±íÖС£ÒýÓòÎÊýʱ£¬»áÏÈ´Ó¾Ö²¿·ûºÅ±íÖвéÕÒ£¬È»ºóÊÇÈ«¾Ö·ûºÅ±í£¬È»ºóÊÇÄÚÖÃÃüÃû±í¡£Òò´Ë£¬È«¾Ö²ÎÊýËäÈ»¿ÉÒÔ±»ÒýÓ㬵«ËüÃDz»ÄÜÔÚº¯ÊýÖÐÖ±½Ó¸³Öµ£¨³ý·ÇËüÃÇÓÃ
796 global Óï¾äÃüÃû£©¡£
797
798 The actual parameters (arguments) to a function call are introduced in
799 the local symbol table of the called function when it is called; thus,
800 arguments are passed using \emph{call by value} (where the
801 \emph{value} is always an object \emph{reference}, not the value of
802 the object).\footnote{
803 Actually, \emph{call by object reference} would be a better
804 description, since if a mutable object is passed, the caller
805 will see any changes the callee makes to it (items
806 inserted into a list).
807 } When a function calls another function, a new local symbol table is
808 created for that call.
809
810 º¯ÊýÒýÓõÄʵ¼Ê²ÎÊýÔÚº¯Êýµ÷ÓÃʱÒýÈë¾Ö²¿·ûºÅ±í£¬Òò´Ë£¬Êµ²Î×ÜÊÇ´«Öµµ÷Óã¨ÕâÀïµÄÖµ×ÜÊÇÒ»¸ö¶ÔÏóÒýÓ㬶ø²»ÊǸöÔÏóµÄÖµ£©¡£\footnote{ÊÂʵÉÏ£¬³ÆÖ®Îªµ÷ÓöÔÏóµÄÒýÓøüºÏÊÊ¡£ÒòΪһ¸ö¿É±ä¶ÔÏ󴫵ݽøÀ´ºó£¬µ÷ÓÃÕß¿ÉÒÔ¿´µ½±»µ÷ÓöÔÏóµÄÈκÎÐ޸ģ¨ÈçÔÚÁ´±íÖвåÈëÒ»¸öеÄ×ÓÏ¡£} Ò»¸öº¯Êý±»ÁíÒ»¸öº¯Êýµ÷ÓÃʱ£¬Ò»¸öеľֲ¿·ûºÅ±íÔÚµ÷Óùý³ÌÖб»´´½¨¡£
811
812 A function definition introduces the function name in the current
813 symbol table. The value of the function name
814 has a type that is recognized by the interpreter as a user-defined
815 function. This value can be assigned to another name which can then
816 also be used as a function. This serves as a general renaming
817 mechanism:
818
819 º¯Êý¶¨ÒåÔÚµ±Ç°·ûºÅ±íÖÐÒýÈ뺯ÊýÃû¡£×÷ΪÓû§¶¨Ò庯Êý£¬º¯ÊýÃûÓÐÒ»¸öΪ½âÊÍÆ÷ÈϿɵÄÀàÐÍÖµ¡£Õâ¸öÖµ¿ÉÒÔ¸³¸øÆäËüÃüÃû£¬Ê¹ÆäÄܹ»×÷Ϊһ¸öº¯ÊýÀ´Ê¹Óá£Õâ¾ÍÏñÒ»¸öÖØÃüÃû»úÖÆ£º
820
821 \begin{verbatim}
822 >>> fib
823 <function fib at 10042ed0>
824 >>> f = fib
825 >>> f(100)
826 1 1 2 3 5 8 13 21 34 55 89
827 \end{verbatim}
828
829 You might object that \code{fib} is not a function but a procedure. In
830 Python, like in C, procedures are just functions that don't return a
831 value. In fact, technically speaking, procedures do return a value,
832 albeit a rather boring one. This value is called \code{None} (it's a
833 built-in name). Writing the value \code{None} is normally suppressed by
834 the interpreter if it would be the only value written. You can see it
835 if you really want to:
836
837 Äã¿ÉÄÜÈÏΪ\code{fib}²»ÊÇÒ»¸öº¯Êý£¨ function £©£¬¶øÊÇÒ»¸ö¹ý³Ì£¨ procedure £©¡£Python ºÍ C Ò»Ñù£¬¹ý³ÌÖ»ÊÇÒ»¸öûÓзµ»ØÖµµÄº¯Êý¡£Êµ¼ÊÉÏ£¬´Ó¼¼ÊõÉϽ²£¬¹ý³ÌÒ²ÓÐÒ»¸ö·µ»ØÖµ£¬ËäÈ»ÊÇÒ»¸ö²»ÌÖÈËϲ»¶µÄ¡£Õâ¸öÖµ±»³ÆÎª \code{None} £¨ÕâÊÇÒ»¸öÄÚÖÃÃüÃû£©¡£Èç¹ûÒ»¸öÖµÖ»ÊÇ None µÄ»°£¬Í¨³£½âÊÍÆ÷²»»áдһ¸ö None ³öÀ´£¬Èç¹ûÄãÕæÏëÒª²é¿´ËüµÄ»°£¬¿ÉÒÔÕâÑù×ö£º
838
839 \begin{verbatim}
840 >>> print fib(0)
841 None
842 \end{verbatim}
843
844 It is simple to write a function that returns a list of the numbers of
845 the Fibonacci series, instead of printing it:
846
847 ÒÔÏÂʾÀýÑÝʾÁËÈçºÎ´Óº¯ÊýÖзµ»ØÒ»¸ö°üº¬·Æ²¨ÄÇÆõÊýÁеÄÊýÖµÁ´±í£¬¶ø²»ÊÇ´òÓ¡Ëü£º
848
849 \begin{verbatim}
850 >>> def fib2(n): # return Fibonacci series up to n
851 ... """Return a list containing the Fibonacci series up to n."""
852 ... result = []
853 ... a, b = 0, 1
854 ... while b < n:
855 ... result.append(b) # see below
856 ... a, b = b, a+b
857 ... return result
858 ...
859 >>> f100 = fib2(100) # call it
860 >>> f100 # write the result
861 [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
862 \end{verbatim}
863
864 This example, as usual, demonstrates some new Python features:
865
866 ºÍÒÔǰһÑù£¬Õâ¸öÀý×ÓÑÝʾÁËһЩÐ嵀 Python ¹¦ÄÜ£º
867
868 \begin{itemize}
869
870 \item
871 The \keyword{return} statement returns with a value from a function.
872 \keyword{return} without an expression argument returns \code{None}.
873 Falling off the end of a procedure also returns \code{None}.
874
875 \keyword{return} Óï¾ä´Óº¯ÊýÖзµ»ØÒ»¸öÖµ£¬²»´ø±í´ïʽµÄ \keyword{return} ·µ»Ø \code{None}¡£¹ý³Ì½áÊøºóÒ²»á·µ»Ø \code{None} ¡£
876
877 \item
878 The statement \code{result.append(b)} calls a \emph{method} of the list
879 object \code{result}. A method is a function that `belongs' to an
880 object and is named \code{obj.methodname}, where \code{obj} is some
881 object (this may be an expression), and \code{methodname} is the name
882 of a method that is defined by the object's type. Different types
883 define different methods. Methods of different types may have the
884 same name without causing ambiguity. (It is possible to define your
885 own object types and methods, using \emph{classes}, as discussed later
886 in this tutorial.)
887 The method \method{append()} shown in the example is defined for
888 list objects; it adds a new element at the end of the list. In this
889 example it is equivalent to \samp{result = result + [b]}, but more
890 efficient.
891
892 Óï¾ä \code{result.append(b)} ³ÆÎªÁ´±í¶ÔÏó \code{result} µÄÒ»¸ö\emph{·½·¨£¨ method £©}¡£·½·¨ÊÇÒ»¸ö¡°ÊôÓÚ¡±Ä³¸ö¶ÔÏóµÄº¯Êý£¬Ëü±»ÃüÃûΪ \code{obj.methodename} £¬ÕâÀïµÄ \code{obj} ÊÇij¸ö¶ÔÏ󣨿ÉÄÜÊÇÒ»¸ö±í´ïʽ£©£¬\code{methodename} ÊÇij¸öÔڸöÔÏóÀàÐͶ¨ÒåÖеķ½·¨µÄÃüÃû¡£²»Í¬µÄÀàÐͶ¨Ò岻ͬµÄ·½·¨¡£²»Í¬ÀàÐÍ¿ÉÄÜÓÐͬÑùÃû×ֵķ½·¨£¬µ«²»»á»ìÏý¡££¨µ±Ä㶨Òå×Ô¼ºµÄ¶ÔÏóÀàÐͺͷ½·¨Ê±£¬¿ÉÄÜ»á³öÏÖÕâÖÖÇé¿ö£¬±¾Ö¸ÄϺóÃæµÄÕ½ڻá½éÉÜÈçºÎʹÓÃ\emph{ÀàÐÍ}£©¡£Ê¾ÀýÖÐÑÝʾµÄ \method{append()}·½·¨ÓÉÁ´±í¶ÔÏó¶¨Ò壬ËüÏòÁ´±íÖмÓÈëÒ»¸öÐÂÔªËØ¡£ÔÚʾÀýÖÐËüµÈͬÓÚ\samp{"result = result + [b]"}£¬²»¹ýЧÂʸü¸ß¡£
893
894 \end{itemize}
895
896 \section{More on Defining Functions ÉîÈ뺯Êý¶¨Òå \label{defining}}
897
898 It is also possible to define functions with a variable number of
899 arguments. There are three forms, which can be combined.
900
901 ÓÐʱÐèÒª¶¨Òå²ÎÊý¸öÊý¿É±äµÄº¯Êý¡£ÓÐÈý¸ö·½·¨¿ÉÒԴﵽĿµÄ£¬ÎÒÃÇ¿ÉÒÔ×éºÏʹÓÃËüÃÇ¡£
902
903 \subsection{Default Argument Values ²ÎÊýĬÈÏÖµ \label{defaultArgs}}
904
905 The most useful form is to specify a default value for one or more
906 arguments. This creates a function that can be called with fewer
907 arguments than it is defined to allow. For example:
908
909 ×îÓÐÓõÄÐÎʽÊǸøÒ»¸ö»ò¶à¸ö²ÎÊýÖ¸¶¨Ä¬ÈÏÖµ¡£ÕâÑù´´½¨µÄº¯Êý¿ÉÒÔÓýÏÉٵIJÎÊýÀ´µ÷Óá£ÀýÈ磺
910
911 \begin{verbatim}
912 def ask_ok(prompt, retries=4, complaint='Yes or no, please!'):
913 while True:
914 ok = raw_input(prompt)
915 if ok in ('y', 'ye', 'yes'): return True
916 if ok in ('n', 'no', 'nop', 'nope'): return False
917 retries = retries - 1
918 if retries < 0: raise IOError, 'refusenik user'
919 print complaint
920 \end{verbatim}
921
922 This function can be called either like this:
923 \code{ask_ok('Do you really want to quit?')} or like this:
924 \code{ask_ok('OK to overwrite the file?', 2)}.
925
926 Õâ¸öº¯Êý»¹¿ÉÒÔÓÃÒÔϵķ½Ê½µ÷Óãº\code{ask_ok('Do you really want
927 to quit?')}£¬»òÕßÏñÕâÑù£º\code{ask_ok('OK to overwrite the file?',
928 2)}¡£
929
930 This example also introduces the \keyword{in} keyword. This tests
931 whether or not a sequence contains a certain value.
932
933 Õâ¸öʾÀý»¹½éÉÜÁ˹ؼü×Ö \keyword{in} ¡£Ëü¼ì²âÒ»¸öÐòÁÐÖÐÊÇ·ñ°üº¬Ä³¸ö¸ø¶¨µÄÖµ¡£
934
935 The default values are evaluated at the point of function definition
936 in the \emph{defining} scope, so that
937
938 ĬÈÏÖµÔÚº¯Êý\emph{¶¨Òå}¶Î±»½âÎö£¬ÈçÏÂËùʾ£º
939
940 \begin{verbatim}
941 i = 5
942
943 def f(arg=i):
944 print arg
945
946 i = 6
947 f()
948 \end{verbatim}
949
950 will print \code{5}.
951
952 ÒÔÉÏ´úÂë»á´òÓ¡5¡£
953
954 \strong{Important warning:} The default value is evaluated only once.
955 This makes a difference when the default is a mutable object such as a
956 list, dictionary, or instances of most classes. For example, the
957 following function accumulates the arguments passed to it on
958 subsequent calls:
959
960 \begin{verbatim}
961 def f(a, L=[]):
962 L.append(a)
963 return L
964
965 print f(1)
966 print f(2)
967 print f(3)
968 \end{verbatim}
969
970 This will print
971
972 Õâ»á´òÓ¡³ö£º
973
974 \begin{verbatim}
975 [1]
976 [1, 2]
977 [1, 2, 3]
978 \end{verbatim}
979
980 If you don't want the default to be shared between subsequent calls,
981 you can write the function like this instead:
982
983 Èç¹ûÄã²»ÏëÔÚ²»Í¬µÄº¯Êýµ÷ÓÃÖ®¼ä¹²Ïí²ÎÊýĬÈÏÖµ£¬¿ÉÒÔÈçÏÂÃæµÄʵÀýÒ»Ñù±àдº¯Êý£º
984
985 \begin{verbatim}
986 def f(a, L=None):
987 if L is None:
988 L = []
989 L.append(a)
990 return L
991 \end{verbatim}
992
993 \subsection{Keyword Arguments \label{keywordArgs}}
994
995 Functions can also be called using
996 keyword arguments of the form \samp{\var{keyword} = \var{value}}. For
997 instance, the following function:
998
999 º¯Êý¿ÉÒÔͨ¹ý¹Ø¼ü×Ö²ÎÊýµÄÐÎʽÀ´µ÷Óã¬ÐÎÈç\samp{\var{keyword} = \var{value}}¡£ÀýÈ磬ÒÔϵĺ¯Êý£º
1000
1001 \begin{verbatim}
1002 def parrot(voltage, state='a stiff', action='voom', type='Norwegian Blue'):
1003 print "-- This parrot wouldn't", action,
1004 print "if you put", voltage, "volts through it."
1005 print "-- Lovely plumage, the", type
1006 print "-- It's", state, "!"
1007 \end{verbatim}
1008
1009 could be called in any of the following ways:
1010
1011 ¿ÉÒÔÓÃÒÔϵÄÈÎÒ»·½·¨µ÷Óãº
1012
1013 \begin{verbatim}
1014 parrot(1000)
1015 parrot(action = 'VOOOOOM', voltage = 1000000)
1016 parrot('a thousand', state = 'pushing up the daisies')
1017 parrot('a million', 'bereft of life', 'jump')
1018 \end{verbatim}
1019
1020 but the following calls would all be invalid:
1021
1022 ²»¹ýÒÔϼ¸ÖÖµ÷ÓÃÊÇÎÞЧµÄ£º
1023
1024 \begin{verbatim}
1025 parrot() # required argument missing
1026 parrot(voltage=5.0, 'dead') # non-keyword argument following keyword
1027 parrot(110, voltage=220) # duplicate value for argument
1028 parrot(actor='John Cleese') # unknown keyword
1029 \end{verbatim}
1030
1031 In general, an argument list must have any positional arguments
1032 followed by any keyword arguments, where the keywords must be chosen
1033 from the formal parameter names. It's not important whether a formal
1034 parameter has a default value or not. No argument may receive a
1035 value more than once --- formal parameter names corresponding to
1036 positional arguments cannot be used as keywords in the same calls.
1037 Here's an example that fails due to this restriction:
1038
1039 ͨ³££¬²ÎÊýÁбíÖеÄÿһ¸ö¹Ø¼ü×Ö¶¼±ØÐëÀ´×ÔÓÚÐÎʽ²ÎÊý£¬Ã¿¸ö²ÎÊý¶¼ÓжÔÓ¦µÄ¹Ø¼ü×Ö¡£ÐÎʽ²ÎÊýÓÐûÓÐĬÈÏÖµ²¢²»ÖØÒª¡£Êµ¼Ê²ÎÊý²»ÄÜÒ»´Î¸³¶à¸öÖµ¡ª¡ªÐÎʽ²ÎÊý²»ÄÜÔÚͬһ´Îµ÷ÓÃÖÐͬʱʹÓÃλÖú͹ؼü×Ö°ó¶¨Öµ¡£ÕâÀïÓÐÒ»¸öÀý×ÓÑÝʾÁËÔÚÕâÖÖÔ¼ÊøÏÂËù³öÏÖµÄʧ°ÜÇé¿ö£º
1040
1041 \begin{verbatim}
1042 >>> def function(a):
1043 ... pass
1044 ...
1045 >>> function(0, a=0)
1046 Traceback (most recent call last):
1047 File "<stdin>", line 1, in ?
1048 TypeError: function() got multiple values for keyword argument 'a'
1049 \end{verbatim}
1050
1051 When a final formal parameter of the form \code{**\var{name}} is
1052 present, it receives a \ulink{dictionary}{../lib/typesmapping.html}
1053 containing all keyword arguments except for those corresponding to
1054 a formal parameter. This may be
1055 combined with a formal parameter of the form
1056 \code{*\var{name}} (described in the next subsection) which receives a
1057 tuple containing the positional arguments beyond the formal parameter
1058 list. (\code{*\var{name}} must occur before \code{**\var{name}}.)
1059 For example, if we define a function like this:
1060
1061 ÒýÈëÒ»¸öÐÎÈç \code{**name} µÄ²ÎÊýʱ£¬Ëü½ÓÊÕÒ»¸ö \ulink{×Öµä}{../lib/typesmapping.html} £¬¸Ã×Öµä°üº¬ÁËËùÓÐδ³öÏÖÔÚÐÎʽ²ÎÊýÁбíÖеĹؼü×Ö²ÎÊý¡£ÕâÀï¿ÉÄÜ»¹»á×éºÏʹÓÃÒ»¸öÐÎÈç \code{*\var{name}} µÄÐÎʽ²ÎÊý£¬Ëü½ÓÊÕÒ»¸öÔª×飨ÏÂÒ»½ÚÖлáÏêϸ½éÉÜ£©£¬°üº¬ÁËËùÓÐûÓгöÏÖÔÚÐÎʽ²ÎÊýÁбíÖеIJÎÊýÖµ¡££¨\code{*\var{name}} ±ØÐëÔÚ \code{**\var{name}} ֮ǰ³öÏÖ£© ÀýÈ磬ÎÒÃÇÕâÑù¶¨ÒåÒ»¸öº¯Êý£º
1062
1063 \begin{verbatim}
1064 def cheeseshop(kind, *arguments, **keywords):
1065 print "-- Do you have any", kind, '?'
1066 print "-- I'm sorry, we're all out of", kind
1067 for arg in arguments: print arg
1068 print '-'*40
1069 keys = keywords.keys()
1070 keys.sort()
1071 for kw in keys: print kw, ':', keywords[kw]
1072 \end{verbatim}
1073
1074 It could be called like this:
1075
1076 Ëü¿ÉÒÔÏñÕâÑùµ÷Óãº
1077
1078 \begin{verbatim}
1079 cheeseshop('Limburger', "It's very runny, sir.",
1080 "It's really very, VERY runny, sir.",
1081 client='John Cleese',
1082 shopkeeper='Michael Palin',
1083 sketch='Cheese Shop Sketch')
1084 \end{verbatim}
1085
1086 and of course it would print:
1087
1088 µ±È»Ëü»á°´ÈçÏÂÄÚÈÝ´òÓ¡£º
1089
1090 \begin{verbatim}
1091 -- Do you have any Limburger ?
1092 -- I'm sorry, we're all out of Limburger
1093 It's very runny, sir.
1094 It's really very, VERY runny, sir.
1095 ----------------------------------------
1096 client : John Cleese
1097 shopkeeper : Michael Palin
1098 sketch : Cheese Shop Sketch
1099 \end{verbatim}
1100
1101 Note that the \method{sort()} method of the list of keyword argument
1102 names is called before printing the contents of the \code{keywords}
1103 dictionary; if this is not done, the order in which the arguments are
1104 printed is undefined.
1105
1106 ×¢Òâ\method{sort()}·½·¨Ôڹؼü×Ö×ÖµäÄÚÈÝ´òӡǰ±»µ÷Ó㬷ñÔòµÄ»°£¬´òÓ¡²ÎÊýʱµÄ˳ÐòÊÇ䶨ÒåµÄ¡£
1107
1108 \subsection{Arbitrary Argument Lists ¿É±ä²ÎÊýÁбí \label{arbitraryArgs}}
1109
1110 Finally, the least frequently used option is to specify that a
1111 function can be called with an arbitrary number of arguments. These
1112 arguments will be wrapped up in a tuple. Before the variable number
1113 of arguments, zero or more normal arguments may occur.
1114
1115 ×îºó£¬Ò»¸ö×î²»³£ÓõÄÑ¡ÔñÊÇ¿ÉÒÔÈú¯Êýµ÷Óÿɱä¸öÊýµÄ²ÎÊý¡£ÕâЩ²ÎÊý±»°ü×°½øÒ»¸öÔª×é¡£ÔÚÕâЩ¿É±ä¸öÊýµÄ²ÎÊý֮ǰ£¬¿ÉÒÔÓÐÁãµ½¶à¸öÆÕͨµÄ²ÎÊý£º
1116
1117 \begin{verbatim}
1118 def fprintf(file, format, *args):
1119 file.write(format % args)
1120 \end{verbatim}
1121
1122
1123 \subsection{Unpacking Argument Lists ²ÎÊýÁбíµÄ·Ö²ð \label{unpacking-arguments}}
1124
1125 The reverse situation occurs when the arguments are already in a list
1126 or tuple but need to be unpacked for a function call requiring separate
1127 positional arguments. For instance, the built-in \function{range()}
1128 function expects separate \var{start} and \var{stop} arguments. If they
1129 are not available separately, write the function call with the
1130 \code{*}-operator to unpack the arguments out of a list or tuple:
1131
1132 ÁíÓÐÒ»ÖÖÏà·´µÄÇé¿ö: µ±ÄãÒª´«µÝµÄ²ÎÊýÒѾÊÇÒ»¸öÁÐ±íµ«Òªµ÷Óõĺ¯ÊýÈ´½ÓÊÜ·Ö¿ªÒ»¸ö¸öµÄ²ÎÊýÖµ. ÕâʱºòÄãÒª°ÑÒÑÓеÄÁбí²ð¿ªÀ´. ÀýÈçÄÚ½¨º¯Êý \function{range()} ÐèÒªÒª¶ÀÁ¢µÄ \var{start}, \var{stop} ²ÎÊý. Äã¿ÉÒÔÔÚµ÷Óú¯Êýʱ¼ÓÒ»¸ö \code{*} ²Ù×÷·ûÀ´×Ô¶¯°Ñ²ÎÊýÁбí²ð¿ª:
1133
1134 \begin{verbatim}
1135 >>> range(3, 6) # normal call with separate arguments
1136 [3, 4, 5]
1137 >>> args = [3, 6]
1138 >>> range(*args) # call with arguments unpacked from a list
1139 [3, 4, 5]
1140 \end{verbatim}
1141
1142 In the same fashion, dictionaries can deliver keyword arguments with the
1143 \code{**}-operator:
1144
1145 ÒÔͬÑùµÄ·½Ê½£¬¿ÉÒÔʹÓà \code{**} ²Ù×÷·û·Ö²ð¹Ø¼ü×Ö²ÎÊýΪ×ֵ䣺
1146
1147 \begin{verbatim}
1148 >>> def parrot(voltage, state='a stiff', action='voom'):
1149 ... print "-- This parrot wouldn't", action,
1150 ... print "if you put", voltage, "volts through it.",
1151 ... print "E's", state, "!"
1152 ...
1153 >>> d = {"voltage": "four million", "state": "bleedin' demised", "action": "VOOM"}
1154 >>> parrot(**d)
1155 -- This parrot wouldn't VOOM if you put four million volts through it. E's bleedin' demised !
1156 \end{verbatim}
1157
1158
1159 \subsection{Lambda Forms Lambda ÐÎʽ \label{lambda}}
1160
1161 By popular demand, a few features commonly found in functional
1162 programming languages like Lisp have been added to Python. With the
1163 \keyword{lambda} keyword, small anonymous functions can be created.
1164 Here's a function that returns the sum of its two arguments:
1165 \samp{lambda a, b: a+b}. Lambda forms can be used wherever function
1166 objects are required. They are syntactically restricted to a single
1167 expression. Semantically, they are just syntactic sugar for a normal
1168 function definition. Like nested function definitions, lambda forms
1169 can reference variables from the containing scope:
1170
1171 ³öÓÚʵ¼ÊÐèÒª£¬Óм¸ÖÖͨ³£ÔÚ¹¦ÄÜÐÔÓïÑÔÀýÈç Lisp ÖгöÏֵŦÄܼÓÈëµ½ÁË Python ¡£Í¨¹ý \keyword{lambda} ¹Ø¼ü×Ö£¬¿ÉÒÔ´´½¨¶ÌСµÄÄäÃûº¯Êý¡£ÕâÀïÓÐÒ»¸öº¯Êý·µ»ØËüµÄÁ½¸ö²ÎÊýµÄºÍ£º\samp{lambda a, b: a+b}¡£ Lambda ÐÎʽ¿ÉÒÔÓÃÓÚÈκÎÐèÒªµÄº¯Êý¶ÔÏó¡£³öÓÚÓï·¨ÏÞÖÆ£¬ËüÃÇÖ»ÄÜÓÐÒ»¸öµ¥¶ÀµÄ±í´ïʽ¡£ÓïÒåÉϽ²£¬ËüÃÇÖ»ÊÇÆÕͨº¯Êý¶¨ÒåÖеÄÒ»¸öÓï·¨¼¼ÇÉ¡£ÀàËÆÓÚǶÌ׺¯Êý¶¨Ò壬lambda ÐÎʽ¿ÉÒÔ´Ó°üº¬·¶Î§ÄÚÒýÓñäÁ¿£º
1172
1173 \begin{verbatim}
1174 >>> def make_incrementor(n):
1175 ... return lambda x: x + n
1176 ...
1177 >>> f = make_incrementor(42)
1178 >>> f(0)
1179 42
1180 >>> f(1)
1181 43
1182 \end{verbatim}
1183
1184
1185 \subsection{Documentation Strings Îĵµ×Ö·û´® \label{docstrings}}
1186
1187 There are emerging conventions about the content and formatting of
1188 documentation strings.
1189 \index{docstrings}\index{documentation strings}
1190 \index{strings, documentation}
1191
1192 ÕâÀï½éÉÜ\index{docstring}\index{Îĵµ×Ö·û´®}µÄ¸ÅÄîºÍ¸ñʽ¡£
1193
1194 The first line should always be a short, concise summary of the
1195 object's purpose. For brevity, it should not explicitly state the
1196 object's name or type, since these are available by other means
1197 (except if the name happens to be a verb describing a function's
1198 operation). This line should begin with a capital letter and end with
1199 a period.
1200
1201 µÚÒ»ÐÐÓ¦¸ÃÊǹØÓÚ¶ÔÏóÓÃ;µÄ¼ò½é¡£¼ò¶ÌÆð¼û£¬²»ÓÃÃ÷È·µÄ³ÂÊö¶ÔÏóÃû»òÀàÐÍ£¬ÒòΪËüÃÇ¿ÉÒÔ´Ó±ðµÄ;¾¶Á˽⵽£¨³ý·ÇÕâ¸öÃû×ÖÅöÇɾÍÊÇÃèÊöÕâ¸öº¯Êý²Ù×÷µÄ¶¯´Ê£©¡£ÕâÒ»ÐÐÓ¦¸ÃÒÔ´óд×Öĸ¿ªÍ·£¬ÒÔ¾äºÅ½áβ¡£
1202
1203 If there are more lines in the documentation string, the second line
1204 should be blank, visually separating the summary from the rest of the
1205 description. The following lines should be one or more paragraphs
1206 describing the object's calling conventions, its side effects, etc.
1207
1208 Èç¹ûÎĵµ×Ö·û´®ÓжàÐУ¬µÚ¶þÐÐÓ¦¸Ã¿Õ³öÀ´£¬Óë½ÓÏÂÀ´µÄÏêϸÃèÊöÃ÷È··Ö¸ô¡£½ÓÏÂÀ´µÄÎĵµÓ¦¸ÃÓÐÒ»»ò¶à¶ÎÃèÊö¶ÔÏóµÄµ÷ÓÃÔ¼¶¨¡¢±ß½çЧӦµÈ¡£
1209
1210 The Python parser does not strip indentation from multi-line string
1211 literals in Python, so tools that process documentation have to strip
1212 indentation if desired. This is done using the following convention.
1213 The first non-blank line \emph{after} the first line of the string
1214 determines the amount of indentation for the entire documentation
1215 string. (We can't use the first line since it is generally adjacent
1216 to the string's opening quotes so its indentation is not apparent in
1217 the string literal.) Whitespace ``equivalent'' to this indentation is
1218 then stripped from the start of all lines of the string. Lines that
1219 are indented less should not occur, but if they occur all their
1220 leading whitespace should be stripped. Equivalence of whitespace
1221 should be tested after expansion of tabs (to 8 spaces, normally).
1222
1223 PythonµÄ½âÊÍÆ÷²»»á´Ó¶àÐеÄÎĵµ×Ö·û´®ÖÐÈ¥³ýËõ½ø£¬ËùÒÔ±ØÒªµÄʱºòÓ¦µ±×Ô¼ºÇå³ýËõ½ø¡£Õâ·ûºÏͨ³£µÄϰ¹ß¡£µÚÒ»ÐÐ\emph{Ö®ºó}µÄµÚÒ»¸ö·Ç¿ÕÐоö¶¨ÁËÕû¸öÎĵµµÄËõ½ø¸ñʽ¡££¨ÎÒÃDz»ÓõÚÒ»ÐÐÊÇÒòΪËüͨ³£½ô¿¿×ÅÆðʼµÄÒýºÅ£¬Ëõ½ø¸ñʽÏÔʾµÄ²»Çå³þ¡££©Áô°×¡°Ï൱ÓÚ¡±ÊÇ×Ö·û´®µÄÆðʼËõ½ø¡£Ã¿Ò»Ðж¼²»Ó¦¸ÃÓÐËõ½ø£¬Èç¹ûÓÐËõ½øµÄ»°£¬ËùÓеÄÁô°×¶¼Ó¦¸ÃÇå³ýµô¡£Áô°×µÄ³¤¶ÈÓ¦µ±µÈÓÚÀ©Õ¹ÖƱí·ûµÄ¿í¶È£¨Í¨³£ÊÇ8¸ö¿Õ¸ñ£©¡£
1224
1225 Here is an example of a multi-line docstring:
1226
1227 ÒÔÏÂÊÇÒ»¸ö¶àÐÐÎĵµ×Ö·û´®µÄʾÀý£º
1228
1229 \begin{verbatim}
1230 >>> def my_function():
1231 ... """Do nothing, but document it.
1232 ...
1233 ... No, really, it doesn't do anything.
1234 ... """
1235 ... pass
1236 ...
1237 >>> print my_function.__doc__
1238 Do nothing, but document it.
1239
1240 No, really, it doesn't do anything.
1241
1242 \end{verbatim}
1243
1244
1245
1246 \chapter{Data Structures Êý¾Ý½á¹¹ \label{structures}}
1247
1248 This chapter describes some things you've learned about already in
1249 more detail, and adds some new things as well.
1250
1251 ±¾Õ½ÚÉîÈë½²ÊöһЩÄãÒѾѧϰ¹ýµÄ¶«Î÷£¬²¢ÇÒ»¹¼ÓÈëÁËеÄÄÚÈÝ¡£
1252
1253 \section{More on Lists ÉîÈëÁ´±í \label{moreLists}}
1254
1255 The list data type has some more methods. Here are all of the methods
1256 of list objects:
1257
1258 Á´±íÀàÐÍÓкܶ෽·¨£¬ÕâÀïÊÇÁ´±íÀàÐ͵ÄËùÓз½·¨£º
1259
1260 \begin{methoddesc}[list]{append}{x}
1261 Add an item to the end of the list;
1262 equivalent to \code{a[len(a):] = [\var{x}]}.
1263
1264 °ÑÒ»¸öÔªËØÌí¼Óµ½Á´±íµÄ½á⣬Ï൱ÓÚ \code{a[len(a):] = [x]}
1265 \end{methoddesc}
1266
1267 \begin{methoddesc}[list]{extend}{L}
1268 Extend the list by appending all the items in the given list;
1269 equivalent to \code{a[len(a):] = \var{L}}.
1270
1271 ͨ¹ýÌí¼ÓÖ¸¶¨Á´±íµÄËùÓÐÔªËØÀ´À©³äÁ´±í£¬Ï൱ÓÚ \code{a[len(a):] = L}¡£
1272 \end{methoddesc}
1273
1274 \begin{methoddesc}[list]{insert}{i, x}
1275 Insert an item at a given position. The first argument is the index
1276 of the element before which to insert, so \code{a.insert(0, \var{x})}
1277 inserts at the front of the list, and \code{a.insert(len(a), \var{x})}
1278 is equivalent to \code{a.append(\var{x})}.
1279
1280 ÔÚÖ¸¶¨Î»ÖòåÈëÒ»¸öÔªËØ¡£µÚÒ»¸ö²ÎÊýÊÇ×¼±¸²åÈëµ½ÆäÇ°ÃæµÄÄǸöÔªËØµÄË÷Òý£¬ÀýÈç\code{a.insert(0,x)}
1281 »á²åÈëµ½Õû¸öÁ´±í֮ǰ£¬¶ø\code{a.insert(len(a), x)} Ï൱ÓÚ
1282 \code{a.append(x)}¡£
1283 \end{methoddesc}
1284
1285 \begin{methoddesc}[list]{remove}{x}
1286 Remove the first item from the list whose value is \var{x}.
1287 It is an error if there is no such item.
1288
1289 ɾ³ýÁ´±íÖÐֵΪ\var{x}µÄµÚÒ»¸öÔªËØ¡£Èç¹ûûÓÐÕâÑùµÄÔªËØ£¬¾Í»á·µ»ØÒ»¸ö´íÎó¡£
1290 \end{methoddesc}
1291
1292 \begin{methoddesc}[list]{pop}{\optional{i}}
1293 Remove the item at the given position in the list, and return it. If
1294 no index is specified, \code{a.pop()} removes and returns the last item
1295 in the list. (The square brackets
1296 around the \var{i} in the method signature denote that the parameter
1297 is optional, not that you should type square brackets at that
1298 position. You will see this notation frequently in the
1299 \citetitle[../lib/lib.html]{Python Library Reference}.)
1300
1301 ´ÓÁ´±íµÄÖ¸¶¨Î»ÖÃɾ³ýÔªËØ£¬²¢½«Æä·µ»Ø¡£Èç¹ûûÓÐÖ¸¶¨Ë÷Òý£¬\code{a.pop()} ·µ»Ø×îºóÒ»¸öÔªËØ¡£ÔªËØËæ¼´´ÓÁ´±íÖб»É¾³ý¡££¨·½·¨ ÖÐ\var{i} Á½±ßµÄ·½À¨ºÅ±íʾÕâ¸ö²ÎÊýÊÇ¿ÉÑ¡µÄ£¬¶ø²»ÊÇÒªÇóÄãÊäÈëÒ»¶Ô·½À¨ºÅ£¬Äã»á¾³£ÔÚ\citetitle[../lib/lib.html]{Python ¿â²Î¿¼ÊÖ²á}ÖÐÓöµ½ÕâÑùµÄ±ê¼Ç¡££©
1302 \end{methoddesc}
1303
1304 \begin{methoddesc}[list]{index}{x}
1305 Return the index in the list of the first item whose value is \var{x}.
1306 It is an error if there is no such item.
1307
1308 ·µ»ØÁ´±íÖеÚÒ»¸öֵΪ \var{x} µÄÔªËØµÄË÷Òý¡£Èç¹ûûÓÐÆ¥ÅäµÄÔªËØ¾Í»á·µ»ØÒ»¸ö´íÎó¡£
1309 \end{methoddesc}
1310
1311 \begin{methoddesc}[list]{count}{x}
1312 Return the number of times \var{x} appears in the list.
1313
1314 ·µ»Ø\var{x}ÔÚÁ´±íÖгöÏֵĴÎÊý¡£
1315 \end{methoddesc}
1316
1317 \begin{methoddesc}[list]{sort}{}
1318 Sort the items of the list, in place.
1319
1320 ¶ÔÁ´±íÖеÄÔªËØ¾ÍµØ£¨ÔÎÄ in place£¬Òâ¼´¸Ã²Ù×÷Ö±½ÓÐ޸ĵ÷ÓÃËüµÄ¶ÔÏ󡪡ªÒëÕߣ©½øÐÐÅÅÐò¡£
1321 \end{methoddesc}
1322
1323 \begin{methoddesc}[list]{reverse}{}
1324 Reverse the elements of the list, in place.
1325
1326 ¾ÍµØ£¨ÔÎÄ in place£¬Òâ¼´¸Ã²Ù×÷Ö±½ÓÐ޸ĵ÷ÓÃËüµÄ¶ÔÏ󡪡ªÒëÕߣ©µ¹ÅÅÁ´±íÖеÄÔªËØ¡£
1327 \end{methoddesc}
1328
1329 An example that uses most of the list methods:
1330
1331 ÏÂÃæÕâ¸öʾÀýÑÝʾÁËÁ´±íµÄ´ó²¿·Ö·½·¨£º
1332
1333 \begin{verbatim}
1334 >>> a = [66.25, 333, 333, 1, 1234.5]
1335 >>> print a.count(333), a.count(66.25), a.count('x')
1336 2 1 0
1337 >>> a.insert(2, -1)
1338 >>> a.append(333)
1339 >>> a
1340 [66.25, 333, -1, 333, 1, 1234.5, 333]
1341 >>> a.index(333)
1342 1
1343 >>> a.remove(333)
1344 >>> a
1345 [66.25, -1, 333, 1, 1234.5, 333]
1346 >>> a.reverse()
1347 >>> a
1348 [333, 1234.5, 1, 333, -1, 66.25]
1349 >>> a.sort()
1350 >>> a
1351 [-1, 1, 66.25, 333, 333, 1234.5]
1352 \end{verbatim}
1353
1354
1355 \subsection{Using Lists as Stacks °ÑÁ´±íµ±×÷¶ÑջʹÓà \label{lists-as-stacks}}
1356 \sectionauthor{Ka-Ping Yee}{[email protected]}
1357
1358 The list methods make it very easy to use a list as a stack, where the
1359 last element added is the first element retrieved (``last-in,
1360 first-out''). To add an item to the top of the stack, use
1361 \method{append()}. To retrieve an item from the top of the stack, use
1362 \method{pop()} without an explicit index. For example:
1363
1364 Á´±í·½·¨Ê¹µÃÁ´±í¿ÉÒԺܷ½±ãµÄ×öΪһ¸ö¶ÑÕ»À´Ê¹Ó㬶ÑÕ»×÷ÎªÌØ¶¨µÄÊý¾Ý½á¹¹£¬×îÏȽøÈëµÄÔªËØ×îºóÒ»¸ö±»ÊÍ·Å£¨ºó½øÏȳö£©¡£ÓÃ\method{append()} ·½·¨¿ÉÒÔ°ÑÒ»¸öÔªËØÌí¼Óµ½¶ÑÕ»¶¥¡£Óò»Ö¸¶¨Ë÷ÒýµÄ\method{pop()} ·½·¨¿ÉÒÔ°ÑÒ»¸öÔªËØ´Ó¶ÑÕ»¶¥ÊͷųöÀ´¡£ÀýÈ磺
1365
1366 \begin{verbatim}
1367 >>> stack = [3, 4, 5]
1368 >>> stack.append(6)
1369 >>> stack.append(7)
1370 >>> stack
1371 [3, 4, 5, 6, 7]
1372 >>> stack.pop()
1373 7
1374 >>> stack
1375 [3, 4, 5, 6]
1376 >>> stack.pop()
1377 6
1378 >>> stack.pop()
1379 5
1380 >>> stack
1381 [3, 4]
1382 \end{verbatim}
1383
1384
1385 \subsection{Using Lists as Queues °ÑÁ´±íµ±×÷¶ÓÁÐʹÓà \label{lists-as-queues}}
1386 \sectionauthor{Ka-Ping Yee}{[email protected]}
1387
1388 You can also use a list conveniently as a queue, where the first
1389 element added is the first element retrieved (``first-in,
1390 first-out''). To add an item to the back of the queue, use
1391 \method{append()}. To retrieve an item from the front of the queue,
1392 use \method{pop()} with \code{0} as the index. For example:
1393
1394 ÄãÒ²¿ÉÒÔ°ÑÁ´±íµ±×ö¶ÓÁÐʹÓ㬶ÓÁÐ×÷ÎªÌØ¶¨µÄÊý¾Ý½á¹¹£¬×îÏȽøÈëµÄÔªËØ×îÏÈÊÍ·Å£¨ÏȽøÏȳö£©¡£Ê¹Óà \method{append()} ·½·¨¿ÉÒÔ°ÑÔªËØÌí¼Óµ½¶ÓÁÐ×îºó£¬ÒÔ0Ϊ²ÎÊýµ÷Óà \method{pop()} ·½·¨¿ÉÒÔ°Ñ×îÏȽøÈëµÄÔªËØÊͷųöÀ´¡£ÀýÈ磺
1395
1396 \begin{verbatim}
1397 >>> queue = ["Eric", "John", "Michael"]
1398 >>> queue.append("Terry") # Terry arrives
1399 >>> queue.append("Graham") # Graham arrives
1400 >>> queue.pop(0)
1401 'Eric'
1402 >>> queue.pop(0)
1403 'John'
1404 >>> queue
1405 ['Michael', 'Terry', 'Graham']
1406 \end{verbatim}
1407
1408
1409 \subsection{Functional Programming Tools º¯Êý»¯±à³Ì¹¤¾ß \label{functional}}
1410
1411 There are three built-in functions that are very useful when used with
1412 lists: \function{filter()}, \function{map()}, and \function{reduce()}.
1413
1414 ¶ÔÓÚÁ´±íÀ´½²£¬ÓÐÈý¸öÄÚÖú¯Êý·Ç³£ÓÐÓãº\function{filter()}£¬
1415 \function{map()}£¬ ºÍ \function{reduce()}¡£
1416
1417 \samp{filter(\var{function}, \var{sequence})} returns a sequence
1418 consisting of those items from the
1419 sequence for which \code{\var{function}(\var{item})} is true.
1420 If \var{sequence} is a \class{string} or \class{tuple}, the result will
1421 be of the same type; otherwise, it is always a \class{list}.
1422 For example, to compute some primes:
1423
1424 \samp{filter(function, sequence)}·µ»ØÒ»¸ö\var{sequence}£¨ÐòÁУ©£¬°üÀ¨Á˸ø¶¨ÐòÁÐÖÐËùÓе÷ÓÃ\code{\var{function}(\var{item})}ºó·µ»ØÖµÎªtrueµÄÔªËØ¡££¨Èç¹û¿ÉÄܵϰ£¬»á·µ»ØÏàͬµÄÀàÐÍ£©¡£Èç¹û \var{sequence} ÊÇÒ»¸ö \class{string} £¨×Ö·û´®£©»òÕß \class{tuple}£¨Ôª×飩£¬·µ»ØÖµ±Ø¶¨ÊÇͬһÀàÐÍ£¬·ñÔò£¬Ëü×ÜÊÇ \class{list}¡£ÀýÈ磬ÒÔϳÌÐò¿ÉÒÔ¼ÆË㲿·ÖËØÊý£º
1425
1426 \begin{verbatim}
1427 >>> def f(x): return x % 2 != 0 and x % 3 != 0
1428 ...
1429 >>> filter(f, range(2, 25))
1430 [5, 7, 11, 13, 17, 19, 23]
1431 \end{verbatim}
1432
1433 \samp{map(\var{function}, \var{sequence})} calls
1434 \code{\var{function}(\var{item})} for each of the sequence's items and
1435 returns a list of the return values. For example, to compute some
1436 cubes:
1437
1438 \samp{map(\var{function}, \var{sequence})} Ϊÿһ¸öÔªËØÒÀ´Îµ÷ÓÃ\code{\var{function}(\var{item})}²¢½«·µ»ØÖµ×é³ÉÒ»¸öÁ´±í·µ»Ø¡£ÀýÈ磬ÒÔϳÌÐò¼ÆËãÁ¢·½£º
1439
1440 \begin{verbatim}
1441 >>> def cube(x): return x*x*x
1442 ...
1443 >>> map(cube, range(1, 11))
1444 [1, 8, 27, 64, 125, 216, 343, 512, 729, 1000]
1445 \end{verbatim}
1446
1447 More than one sequence may be passed; the function must then have as
1448 many arguments as there are sequences and is called with the
1449 corresponding item from each sequence (or \code{None} if some sequence
1450 is shorter than another). For example:
1451
1452 ¿ÉÒÔ´«Èë¶à¸öÐòÁУ¬º¯ÊýÒ²±ØÐëÒªÓжÔÓ¦ÊýÁ¿µÄ²ÎÊý£¬Ö´ÐÐʱ»áÒÀ´ÎÓø÷ÐòÁÐÉ϶ÔÓ¦µÄÔªËØÀ´µ÷Óú¯Êý£¨Èç¹ûijЩÐòÁÐ±ÈÆäËüµÄ¶Ì£¬¾ÍÓÃ\code{None}À´´úÌæ£©¡£Èç¹û°ÑNone×öΪһ¸öº¯Êý´«È룬ÔòÖ±½Ó·µ»Ø²ÎÊý×öÎªÌæ´ú¡£ÀýÈ磺
1453
1454 \begin{verbatim}
1455 >>> seq = range(8)
1456 >>> def add(x, y): return x+y
1457 ...
1458 >>> map(add, seq, seq)
1459 [0, 2, 4, 6, 8, 10, 12, 14]
1460 \end{verbatim}
1461
1462 \samp{reduce(\var{function}, \var{sequence})} returns a single value
1463 constructed by calling the binary function \var{function} on the first two
1464 items of the sequence, then on the result and the next item, and so
1465 on. For example, to compute the sum of the numbers 1 through 10:
1466
1467 \samp{reduce(\var{func}, \var{sequence})} ·µ»ØÒ»¸öµ¥Öµ£¬ËüÊÇÕâÑù¹¹ÔìµÄ£ºÊ×ÏÈÒÔÐòÁеÄǰÁ½¸öÔªËØµ÷Óú¯Êý£¬ÔÙÒÔ·µ»ØÖµºÍµÚÈý¸ö²ÎÊýµ÷Óã¬ÒÀ´ÎÖ´ÐÐÏÂÈ¥¡£ÀýÈ磬ÒÔϳÌÐò¼ÆËã1µ½10µÄÕûÊýÖ®ºÍ£º
1468
1469 \begin{verbatim}
1470 >>> def add(x,y): return x+y
1471 ...
1472 >>> reduce(add, range(1, 11))
1473 55
1474 \end{verbatim}
1475
1476 If there's only one item in the sequence, its value is returned; if
1477 the sequence is empty, an exception is raised.
1478
1479 Èç¹ûÐòÁÐÖÐÖ»ÓÐÒ»¸öÔªËØ£¬¾Í·µ»ØËü£¬Èç¹ûÐòÁÐÊǿյ쬾ÍÅ׳öÒ»¸öÒì³£¡£
1480
1481 A third argument can be passed to indicate the starting value. In this
1482 case the starting value is returned for an empty sequence, and the
1483 function is first applied to the starting value and the first sequence
1484 item, then to the result and the next item, and so on. For example,
1485
1486 ¿ÉÒÔ´«ÈëµÚÈý¸ö²ÎÊý×öΪ³õʼֵ¡£Èç¹ûÐòÁÐÊǿյģ¬¾Í·µ»Ø³õʼֵ£¬·ñÔòº¯Êý»áÏȽÓÊÕ³õʼֵºÍÐòÁеĵÚÒ»¸öÔªËØ£¬È»ºóÊÇ·µ»ØÖµºÍÏÂÒ»¸öÔªËØ£¬ÒÀ´ËÀàÍÆ¡£ÀýÈ磺
1487
1488 \begin{verbatim}
1489 >>> def sum(seq):
1490 ... def add(x,y): return x+y
1491 ... return reduce(add, seq, 0)
1492 ...
1493 >>> sum(range(1, 11))
1494 55
1495 >>> sum([])
1496 0
1497 \end{verbatim}
1498
1499 Don't use this example's definition of \function{sum()}: since summing
1500 numbers is such a common need, a built-in function
1501 \code{sum(\var{sequence})} is already provided, and works exactly like
1502 this.
1503 ²»ÒªÏñʾÀýÖÐÕâÑù¶¨Òå\function{sum()}£ºÒòΪºÏ¼ÆÊýÖµÊÇÒ»¸öͨÓõÄÐèÇó£¬ÔÚ2.3°æÖУ¬ÌṩÁËÄÚÖõÄ\code{sum(\var{sequence})} º¯Êý¡£
1504 \versionadded{2.3}
1505
1506 \subsection{List Comprehensions Á´±íÍÆµ¼Ê½}
1507
1508 List comprehensions provide a concise way to create lists without resorting
1509 to use of \function{map()}, \function{filter()} and/or \keyword{lambda}.
1510 The resulting list definition tends often to be clearer than lists built
1511 using those constructs. Each list comprehension consists of an expression
1512 followed by a \keyword{for} clause, then zero or more \keyword{for} or
1513 \keyword{if} clauses. The result will be a list resulting from evaluating
1514 the expression in the context of the \keyword{for} and \keyword{if} clauses
1515 which follow it. If the expression would evaluate to a tuple, it must be
1516 parenthesized.
1517
1518 Á´±íÍÆµ¼Ê½ÌṩÁËÒ»¸ö´´½¨Á´±íµÄ¼òµ¥Í¾¾¶£¬ÎÞÐèʹÓÃ\function{map()}£¬ \function{filter()} ÒÔ¼° \keyword{lambda}¡£·µ»ØÁ´±íµÄ¶¨Òåͨ³£Òª±È´´½¨ÕâЩÁ´±í¸üÇåÎú¡£Ã¿Ò»¸öÁ´±íÍÆµ¼Ê½°üÀ¨ÔÚÒ»¸ö\keyword{for} Óï¾äÖ®ºóµÄ±í´ïʽ£¬Áã»ò¶à¸ö \keyword{for}»ò \keyword{if} Óï¾ä¡£·µ»ØÖµÊÇÓÉ \keyword{for} »ò \keyword{if}×Ó¾äÖ®ºóµÄ±í´ïʽµÃµ½µÄÔªËØ×é³ÉµÄÁ´±í¡£Èç¹ûÏëÒªµÃµ½Ò»¸öÔª×飬±ØÐëÒª¼ÓÉÏÀ¨ºÅ¡£
1519
1520 \begin{verbatim}
1521 >>> freshfruit = [' banana', ' loganberry ', 'passion fruit ']
1522 >>> [weapon.strip() for weapon in freshfruit]
1523 ['banana', 'loganberry', 'passion fruit']
1524 >>> vec = [2, 4, 6]
1525 >>> [3*x for x in vec]
1526 [6, 12, 18]
1527 >>> [3*x for x in vec if x > 3]
1528 [12, 18]
1529 >>> [3*x for x in vec if x < 2]
1530 []
1531 >>> [[x,x**2] for x in vec]
1532 [[2, 4], [4, 16], [6, 36]]
1533 >>> [x, x**2 for x in vec] # error - parens required for tuples
1534 File "<stdin>", line 1, in ?
1535 [x, x**2 for x in vec]
1536 ^
1537 SyntaxError: invalid syntax
1538 >>> [(x, x**2) for x in vec]
1539 [(2, 4), (4, 16), (6, 36)]
1540 >>> vec1 = [2, 4, 6]
1541 >>> vec2 = [4, 3, -9]
1542 >>> [x*y for x in vec1 for y in vec2]
1543 [8, 6, -18, 16, 12, -36, 24, 18, -54]
1544 >>> [x+y for x in vec1 for y in vec2]
1545 [6, 5, -7, 8, 7, -5, 10, 9, -3]
1546 >>> [vec1[i]*vec2[i] for i in range(len(vec1))]
1547 [8, 12, -54]
1548 \end{verbatim}
1549
1550 List comprehensions are much more flexible than \function{map()} and can be
1551 applied to complex expressions and nested functions:
1552
1553 Á´±íÍÆµ¼Ê½±È \function{map()}¸ü¸´ÔÓ£¬¿ÉʹÓø´Ôӵıí´ïʽºÍǶÌ׺¯Êý¡£
1554
1555 \begin{verbatim}
1556 >>> [str(round(355/113.0, i)) for i in range(1,6)]
1557 ['3.1', '3.14', '3.142', '3.1416', '3.14159']
1558 \end{verbatim}
1559
1560
1561 \section{The \keyword{del} statement \keyword{del}Óï¾ä \label{del}}
1562
1563 There is a way to remove an item from a list given its index instead
1564 of its value: the \keyword{del} statement. This differs from the
1565 \method{pop()}) method which returns a value. The \keyword{del}
1566 statement can also be used to remove slices from a list or clear the
1567 entire list (which we did earlier by assignment of an empty list to
1568 the slice). For example:
1569
1570 ÓÐÒ»¸ö·½·¨¿É´ÓÁ´±íÖÐɾ³ýÖ¸¶¨Ë÷ÒýµÄÔªËØ£º\keyword{del} Óï¾ä¡£Óë·µ»Ø±äÁ¿ÖµµÄ \method{pop()} ·½·¨²»Í¬£¬del Óï¾äÒ²¿ÉÒÔ´ÓÒ»¸öÁ´±íÖÐÒÆ×ßÇи·Ö»òÕßÕû¸öÁ´±í(¾ÍÏñÎÒÃÇÔçÏȽ«Ò»¸ö¿ÕÁ´±í¸³¸øÇи·Ö)¡£ÀýÈ磺
1571
1572 \begin{verbatim}
1573 >>> a = [-1, 1, 66.25, 333, 333, 1234.5]
1574 >>> del a[0]
1575 >>> a
1576 [1, 66.25, 333, 333, 1234.5]
1577 >>> del a[2:4]
1578 >>> a
1579 [1, 66.25, 1234.5]
1580 >>> del a[:]
1581 >>> a
1582 []
1583 \end{verbatim}
1584
1585 \keyword{del} can also be used to delete entire variables:
1586
1587 \keyword{del} Ò²¿ÉÒÔÓÃÓÚɾ³ýÕû¸ö±äÁ¿£º
1588
1589 \begin{verbatim}
1590 >>> del a
1591 \end{verbatim}
1592
1593 Referencing the name \code{a} hereafter is an error (at least until
1594 another value is assigned to it). We'll find other uses for
1595 \keyword{del} later.
1596
1597 ´ËºóÔÙÒýÓÃÕâ¸öÃû×ֻᷢÉú´íÎó£¨ÖÁÉÙÒªµ½¸øËü¸³ÁíÒ»¸öֵΪֹ£©¡£ºóÃæÎÒÃÇ»¹»á·¢ÏÖ\keyword{del}µÄÆäËüÓ÷¨¡£
1598
1599 \section{Tuples and Sequences Ôª×éºÍÐòÁÐ \label{tuples}}
1600
1601 We saw that lists and strings have many common properties, such as
1602 indexing and slicing operations. They are two examples of
1603 \ulink{\emph{sequence} data types}{../lib/typesseq.html}. Since
1604 Python is an evolving language, other sequence data types may be
1605 added. There is also another standard sequence data type: the
1606 \emph{tuple}.
1607
1608 ÎÒÃÇÖªµÀÁ´±íºÍ×Ö·û´®ÓкܶàͨÓõÄÊôÐÔ£¬ÀýÈçË÷ÒýºÍÇиî²Ù×÷¡£ËüÃÇÊÇÐòÁÐÀàÐÍÖеÄÁ½ÖÖ¡£ÒòΪPythonÊÇÒ»¸öÔÚ²»Í£½ø»¯µÄÓïÑÔ£¬Ò²¿ÉÄÜ»á¼ÓÈëÆäËüµÄ\ulink{\emph{ÐòÁÐ}ÀàÐÍ}{../lib/typesseq.html}£¬ÕâÀïÓÐÁíÒ»ÖÖ±ê×¼ÐòÁÐÀàÐÍ£º\emph{Ôª×é}¡£
1609
1610 A tuple consists of a number of values separated by commas, for
1611 instance:
1612
1613 Ò»¸öÔª×éÓÉÊý¸ö¶ººÅ·Ö¸ôµÄÖµ×é³É£¬ÀýÈ磺
1614
1615 \begin{verbatim}
1616 >>> t = 12345, 54321, 'hello!'
1617 >>> t[0]
1618 12345
1619 >>> t
1620 (12345, 54321, 'hello!')
1621 >>> # Tuples may be nested:
1622 ... u = t, (1, 2, 3, 4, 5)
1623 >>> u
1624 ((12345, 54321, 'hello!'), (1, 2, 3, 4, 5))
1625 \end{verbatim}
1626
1627 As you see, on output tuples are always enclosed in parentheses, so
1628 that nested tuples are interpreted correctly; they may be input with
1629 or without surrounding parentheses, although often parentheses are
1630 necessary anyway (if the tuple is part of a larger expression).
1631
1632 ÈçÄãËù¼û£¬Ôª×éÔÚÊä³öʱ×ÜÊÇÓÐÀ¨ºÅµÄ£¬ÒÔ±ãÓÚÕýÈ·±í´ïǶÌ׽ṹ¡£ÔÚÊäÈëʱ¿ÉÄÜÓлòûÓÐÀ¨ºÅ¶¼¿ÉÒÔ£¬²»¹ý¾³£À¨ºÅ¶¼ÊDZØÐëµÄ£¨Èç¹ûÔª×éÊÇÒ»¸ö¸ü´óµÄ±í´ïʽµÄÒ»²¿·Ö£©¡£
1633
1634 Tuples have many uses. For example: (x, y) coordinate pairs, employee
1635 records from a database, etc. Tuples, like strings, are immutable: it
1636 is not possible to assign to the individual items of a tuple (you can
1637 simulate much of the same effect with slicing and concatenation,
1638 though). It is also possible to create tuples which contain mutable
1639 objects, such as lists.
1640
1641 Ôª×éÓкܶàÓÃ;¡£ÀýÈç(x, y)×ø±êµã£¬Êý¾Ý¿âÖеÄÔ±¹¤¼Ç¼µÈµÈ¡£Ôª×é¾ÍÏñ×Ö·û´®£¬²»¿É¸Ä±ä£º²»ÄܸøÔª×éµÄÒ»¸ö¶ÀÁ¢µÄÔªËØ¸³Öµ£¨¾¡¹ÜÄã¿ÉÒÔͨ¹ýÁª½ÓºÍÇиîÀ´Ä£·Â£©¡£Ò²¿ÉÒÔͨ¹ý°üº¬¿É±ä¶ÔÏóÀ´´´½¨Ôª×飬ÀýÈçÁ´±í¡£
1642
1643 A special problem is the construction of tuples containing 0 or 1
1644 items: the syntax has some extra quirks to accommodate these. Empty
1645 tuples are constructed by an empty pair of parentheses; a tuple with
1646 one item is constructed by following a value with a comma
1647 (it is not sufficient to enclose a single value in parentheses).
1648 Ugly, but effective. For example:
1649
1650 Ò»¸öÌØÊâµÄÎÊÌâÊǹ¹Ôì°üº¬Áã¸ö»òÒ»¸öÔªËØµÄÔª×飺ΪÁËÊÊÓ¦ÕâÖÖÇé¿ö£¬Óï·¨ÉÏÓÐһЩ¶îÍâµÄ¸Ä±ä¡£Ò»¶Ô¿ÕµÄÀ¨ºÅ¿ÉÒÔ´´½¨¿ÕÔª×飻Ҫ´´½¨Ò»¸öµ¥ÔªËØÔª×é¿ÉÒÔÔÚÖµºóÃæ¸úÒ»¸ö¶ººÅ£¨ÔÚÀ¨ºÅÖзÅÈëÒ»¸öµ¥ÖµÊDz»¹»µÄ£©¡£³óª£¬µ«ÊÇÓÐЧ¡£ÀýÈ磺
1651
1652 \begin{verbatim}
1653 >>> empty = ()
1654 >>> singleton = 'hello', # <-- note trailing comma
1655 >>> len(empty)
1656 0
1657 >>> len(singleton)
1658 1
1659 >>> singleton
1660 ('hello',)
1661 \end{verbatim}
1662
1663 The statement \code{t = 12345, 54321, 'hello!'} is an example of
1664 \emph{tuple packing}: the values \code{12345}, \code{54321} and
1665 \code{'hello!'} are packed together in a tuple. The reverse operation
1666 is also possible:
1667
1668 Óï¾ä t = 12345, 54321, 'hello!' ÊÇÔª×é·â×°£¨sequence packing£©µÄÒ»¸öÀý×Ó£ºÖµ 12345£¬ 54321 ºÍ 'hello!' ±»·â×°½øÔª×é¡£ÆäÄæ²Ù×÷¿ÉÄÜÊÇÕâÑù£º
1669
1670 \begin{verbatim}
1671 >>> x, y, z = t
1672 \end{verbatim}
1673
1674 This is called, appropriately enough, \emph{sequence unpacking}.
1675 Sequence unpacking requires the list of variables on the left to
1676 have the same number of elements as the length of the sequence. Note
1677 that multiple assignment is really just a combination of tuple packing
1678 and sequence unpacking!
1679
1680 Õâ¸öµ÷Óñ»³ÆÎª\emph{ÐòÁвð·â}·Ç³£ºÏÊÊ¡£ÐòÁвð·âÒªÇó×ó²àµÄ±äÁ¿ÊýÄ¿ÓëÐòÁеÄÔªËØ¸öÊýÏàͬ¡£Òª×¢ÒâµÄÊǿɱä²ÎÊý£¨multiple assignment £©ÆäʵֻÊÇÔª×é·â×°ºÍÐòÁвð·âµÄÒ»¸ö½áºÏ£¡
1681
1682 There is a small bit of asymmetry here: packing multiple values
1683 always creates a tuple, and unpacking works for any sequence.
1684
1685 ÕâÀïÓÐÒ»µã²»¶Ô³Æ£º·â×°¶àÖØ²ÎÊýͨ³£»á´´½¨Ò»¸öÔª×飬¶ø²ð·â²Ù×÷¿ÉÒÔ×÷ÓÃÓÚÈκÎÐòÁС£
1686
1687 % XXX Add a bit on the difference between tuples and lists.
1688
1689
1690 \section{Sets ¼¯ºÏ \label{sets}}
1691
1692 Python also includes a data type for \emph{sets}. A set is an unordered
1693 collection with no duplicate elements. Basic uses include membership
1694 testing and eliminating duplicate entries. Set objects also support
1695 mathematical operations like union, intersection, difference, and
1696 symmetric difference.
1697
1698 Python »¹°üº¬ÁËÒ»¸öÊý¾ÝÀàÐÍ¡ª¡ª \emph{set}£¨¼¯ºÏ£©¡£¼¯ºÏÊÇÒ»¸öÎÞÐò²»Öظ´ÔªËص£»ù±¾¹¦ÄܰüÀ¨¹ØÏµ²âÊÔºÍÏû³ýÖØ¸´ÔªËØ¡£¼¯ºÏ¶ÔÏó»¹Ö§³Ö union£¨ÁªºÏ£©£¬intersection£¨½»£©£¬difference£¨²î£©ºÍsysmmetric difference£¨¶Ô³Æ²î¼¯£©µÈÊýѧÔËËã¡£
1699
1700 Here is a brief demonstration:
1701
1702 ÒÔÏÂÊÇÒ»¸ö¼òµ¥µÄÑÝʾ£º
1703
1704 \begin{verbatim}
1705 >>> basket = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana']
1706 >>> fruit = set(basket) # create a set without duplicates
1707 >>> fruit
1708 set(['orange', 'pear', 'apple', 'banana'])
1709 >>> 'orange' in fruit # fast membership testing
1710 True
1711 >>> 'crabgrass' in fruit
1712 False
1713
1714 >>> # Demonstrate set operations on unique letters from two words
1715 ...
1716 >>> a = set('abracadabra')
1717 >>> b = set('alacazam')
1718 >>> a # unique letters in a
1719 set(['a', 'r', 'b', 'c', 'd'])
1720 >>> a - b # letters in a but not in b
1721 set(['r', 'd', 'b'])
1722 >>> a | b # letters in either a or b
1723 set(['a', 'c', 'r', 'd', 'b', 'm', 'z', 'l'])
1724 >>> a & b # letters in both a and b
1725 set(['a', 'c'])
1726 >>> a ^ b # letters in a or b but not both
1727 set(['r', 'd', 'b', 'm', 'z', 'l'])
1728 \end{verbatim}
1729
1730
1731 \section{Dictionaries ×Öµä \label{dictionaries}}
1732
1733 Another useful data type built into Python is the
1734 \ulink{\emph{dictionary}}{../lib/typesmapping.html}.
1735 Dictionaries are sometimes found in other languages as ``associative
1736 memories'' or ``associative arrays''. Unlike sequences, which are
1737 indexed by a range of numbers, dictionaries are indexed by \emph{keys},
1738 which can be any immutable type; strings and numbers can always be
1739 keys. Tuples can be used as keys if they contain only strings,
1740 numbers, or tuples; if a tuple contains any mutable object either
1741 directly or indirectly, it cannot be used as a key. You can't use
1742 lists as keys, since lists can be modified in place using
1743 index assignments, slice assignments, or methods like
1744 \method{append()} and \method{extend()}.
1745
1746 ÁíÒ»¸ö·Ç³£ÓÐÓõÄPythonÄÚ½¨Êý¾ÝÀàÐÍÊÇ\ulink{\emph{×Öµä}}{../lib/typesmapping.html}¡£×ÖµäÔÚijЩÓïÑÔÖпÉÄܳÆÎª¡°ÁªºÏÄڴ桱£¨``associative memories''£©»ò¡°ÁªºÏÊý×顱£¨``associative arrays''£©¡£ÐòÁÐÊÇÒÔÁ¬ÐøµÄÕûÊýΪË÷Òý£¬Óë´Ë²»Í¬µÄÊÇ£¬×ÖµäÒÔ\emph{¹Ø¼ü×Ö}ΪË÷Òý£¬¹Ø¼ü×Ö¿ÉÒÔÊÇÈÎÒâ²»¿É±äÀàÐÍ£¬Í¨³£ÓÃ×Ö·û´®»òÊýÖµ¡£Èç¹ûÔª×éÖÐÖ»°üº¬×Ö·û´®ºÍÊý×Ö£¬Ëü¿ÉÒÔ×öΪ¹Ø¼ü×Ö£¬Èç¹ûËüÖ±½Ó»ò¼ä½ÓµÄ°üº¬Á˿ɱä¶ÔÏ󣬾Ͳ»Äܵ±×ö¹Ø¼ü×Ö¡£²»ÄÜÓÃÁ´±í×ö¹Ø¼ü×Ö£¬ÒòΪÁ´±í¿ÉÒÔÓÃË÷Òý¡¢Çиî»òÕß \method{append()} ºÍ \method{extend()}µÈ·½·¨¸Ä±ä¡£
1747
1748 It is best to think of a dictionary as an unordered set of
1749 \emph{key: value} pairs, with the requirement that the keys are unique
1750 (within one dictionary).
1751 A pair of braces creates an empty dictionary: \code{\{\}}.
1752 Placing a comma-separated list of key:value pairs within the
1753 braces adds initial key:value pairs to the dictionary; this is also the
1754 way dictionaries are written on output.
1755
1756 Àí½â×ÖµäµÄ×î¼Ñ·½Ê½ÊǰÑËü¿´×öÎÞÐòµÄ\emph{¹Ø¼ü×Ö£ºÖµ} ¶Ô£¨key:value pairs£©¼¯ºÏ£¬¹Ø¼ü×Ö±ØÐëÊÇ»¥²»ÏàͬµÄ£¨ÔÚͬһ¸ö×ÖµäÖ®ÄÚ£©¡£Ò»¶Ô´óÀ¨ºÅ´´½¨Ò»¸ö¿ÕµÄ×ֵ䣺\code{\{\}}¡£³õʼ»¯Á´±íʱ£¬ÔÚ´óÀ¨ºÅÄÚ·ÅÖÃÒ»×鶺ºÅ·Ö¸ôµÄ¹Ø¼ü×Ö£ºÖµ¶Ô£¬ÕâÒ²ÊÇ×ÖµäÊä³öµÄ·½Ê½¡£
1757
1758 The main operations on a dictionary are storing a value with some key
1759 and extracting the value given the key. It is also possible to delete
1760 a key:value pair
1761 with \code{del}.
1762 If you store using a key that is already in use, the old value
1763 associated with that key is forgotten. It is an error to extract a
1764 value using a non-existent key.
1765
1766 ×ÖµäµÄÖ÷Òª²Ù×÷ÊÇÒÀ¾Ý¹Ø¼ü×ÖÀ´´æ´¢ºÍÎöȡֵ¡£Ò²¿ÉÒÔÓà \code{del} À´É¾³ý¹Ø¼ü×Ö£ºÖµ¶Ô£¨key:value£©¡£Èç¹ûÄãÓÃÒ»¸öÒѾ´æÔڵĹؼü×Ö´æ´¢Öµ£¬ÒÔǰΪ¸Ã¹Ø¼ü×Ö·ÖÅäµÄÖµ¾Í»á±»ÒÅÍü¡£ÊÔͼÎöÈ¡´ÓÒ»¸ö²»´æÔڵĹؼü×ÖÖжÁȡֵ»áµ¼Ö´íÎó¡£
1767
1768 The \method{keys()} method of a dictionary object returns a list of all
1769 the keys used in the dictionary, in arbitrary order (if you want it
1770 sorted, just apply the \method{sort()} method to the list of keys). To
1771 check whether a single key is in the dictionary, either use the dictionary's
1772 \method{has_key()} method or the \keyword{in} keyword.
1773
1774 ×ÖµäµÄ \method{keys()}·½·¨·µ»ØÓÉËùÓйؼü×Ö×é³ÉµÄÁ´±í£¬¸ÃÁ´±íµÄ˳Ðò²»¶¨£¨Èç¹ûÄãÐèÒªËüÓÐÐò£¬Ö»Äܵ÷Óùؼü×ÖÁ´±íµÄ\method{sort()} ·½·¨£©¡£Ê¹ÓÃ×ÖµäµÄ \method{has_key()}·½·¨»ò in ¹Ø¼ü×Ö¿ÉÒÔ¼ì²é×ÖµäÖÐÊÇ·ñ´æÔÚijһ¹Ø¼ü×Ö¡£
1775
1776 Here is a small example using a dictionary:
1777
1778 ÕâÊÇÒ»¸ö¹ØÓÚ×ÖµäÓ¦ÓõÄСʾÀý£º
1779
1780 \begin{verbatim}
1781 >>> tel = {'jack': 4098, 'sape': 4139}
1782 >>> tel['guido'] = 4127
1783 >>> tel
1784 {'sape': 4139, 'guido': 4127, 'jack': 4098}
1785 >>> tel['jack']
1786 4098
1787 >>> del tel['sape']
1788 >>> tel['irv'] = 4127
1789 >>> tel
1790 {'guido': 4127, 'irv': 4127, 'jack': 4098}
1791 >>> tel.keys()
1792 ['guido', 'irv', 'jack']
1793 >>> tel.has_key('guido')
1794 True
1795 >>> 'guido' in tel
1796 True
1797 \end{verbatim}
1798
1799 The \function{dict()} constructor builds dictionaries directly from
1800 lists of key-value pairs stored as tuples. When the pairs form a
1801 pattern, list comprehensions can compactly specify the key-value list.
1802
1803 Á´±íÖд洢¹Ø¼ü×Ö-Öµ¶ÔÔª×éµÄ»°£¬\function{dict()} ¿ÉÒÔ´ÓÖÐÖ±½Ó¹¹Ôì×ֵ䡣¹Ø¼ü×Ö-Öµ¶ÔÀ´×Ôij¸öÌØ¶¨Ä£Ê½Ê±£¬¿ÉÒÔÓÃÁ´±íÍÆµ¼Ê½¼òµ¥µÄÉú³É¹Ø¼ü×Ö-ÖµÁ´±í¡£
1804
1805 \begin{verbatim}
1806 >>> dict([('sape', 4139), ('guido', 4127), ('jack', 4098)])
1807 {'sape': 4139, 'jack': 4098, 'guido': 4127}
1808 >>> dict([(x, x**2) for x in (2, 4, 6)]) # use a list comprehension
1809 {2: 4, 4: 16, 6: 36}
1810 \end{verbatim}
1811
1812 Later in the tutorial, we will learn about Generator Expressions
1813 which are even better suited for the task of supplying key-values pairs to
1814 the \function{dict()} constructor.
1815
1816 ÔÚÈëÃÅÖ¸ÄϺóÃæµÄÄÚÈÝÖУ¬ÎÒÃǽ«»áѧϰ¸üÊÊÓÚΪ \function{dict()} ¹¹ÔìÆ÷Éú³É¼üÖµ¶ÔµÄÉú³ÉÆ÷±í´ïʽ¡£
1817
1818 When the keys are simple strings, it is sometimes easier to specify
1819 pairs using keyword arguments:
1820
1821 ʹÓüòµ¥×Ö·û´®×÷Ϊ¹Ø¼ü×ֵϰ£¬Í¨³£Óùؼü×Ö²ÎÊý¸ü¼òµ¥¡£
1822
1823 \begin{verbatim}
1824 >>> dict(sape=4139, guido=4127, jack=4098)
1825 {'sape': 4139, 'jack': 4098, 'guido': 4127}
1826 \end{verbatim}
1827
1828
1829 \section{Looping Techniques Ñ»·¼¼Êõ \label{loopidioms}}
1830
1831 When looping through dictionaries, the key and corresponding value can
1832 be retrieved at the same time using the \method{iteritems()} method.
1833
1834 ÔÚ×ÖµäÖÐÑ»·Ê±£¬¹Ø¼ü×ֺͶÔÓ¦µÄÖµ¿ÉÒÔʹÓà \method{iteritems()}·½·¨Í¬Ê±½â¶Á³öÀ´¡£
1835
1836 \begin{verbatim}
1837 >>> knights = {'gallahad': 'the pure', 'robin': 'the brave'}
1838 >>> for k, v in knights.iteritems():
1839 ... print k, v
1840 ...
1841 gallahad the pure
1842 robin the brave
1843 \end{verbatim}
1844
1845 When looping through a sequence, the position index and corresponding
1846 value can be retrieved at the same time using the
1847 \function{enumerate()} function.
1848
1849 ÔÚÐòÁÐÖÐÑ»·Ê±£¬Ë÷ÒýλÖúͶÔÓ¦Öµ¿ÉÒÔʹÓÃ\function{enumerate()}º¯ÊýͬʱµÃµ½¡£
1850
1851 \begin{verbatim}
1852 >>> for i, v in enumerate(['tic', 'tac', 'toe']):
1853 ... print i, v
1854 ...
1855 0 tic
1856 1 tac
1857 2 toe
1858 \end{verbatim}
1859
1860 To loop over two or more sequences at the same time, the entries
1861 can be paired with the \function{zip()} function.
1862
1863 ͬʱѻ·Á½¸ö»ò¸ü¶àµÄÐòÁУ¬¿ÉÒÔʹÓà \function{zip()} ÕûÌå½â¶Á¡£
1864
1865 \begin{verbatim}
1866 >>> questions = ['name', 'quest', 'favorite color']
1867 >>> answers = ['lancelot', 'the holy grail', 'blue']
1868 >>> for q, a in zip(questions, answers):
1869 ... print 'What is your %s? It is %s.' % (q, a)
1870 ...
1871 What is your name? It is lancelot.
1872 What is your quest? It is the holy grail.
1873 What is your favorite color? It is blue.
1874 \end{verbatim}
1875
1876 To loop over a sequence in reverse, first specify the sequence
1877 in a forward direction and then call the \function{reversed()}
1878 function.
1879
1880 Ðè񻀾ÏòÑ»·ÐòÁеϰ£¬ÏÈÕýÏò¶¨Î»ÐòÁУ¬È»ºóµ÷Óà \function{reversed()} º¯Êý
1881
1882 \begin{verbatim}
1883 >>> for i in reversed(xrange(1,10,2)):
1884 ... print i
1885 ...
1886 9
1887 7
1888 5
1889 3
1890 1
1891 \end{verbatim}
1892
1893 To loop over a sequence in sorted order, use the \function{sorted()}
1894 function which returns a new sorted list while leaving the source
1895 unaltered.
1896
1897 Òª°´ÅÅÐòºóµÄ˳ÐòÑ»·ÐòÁеϰ£¬Ê¹Óà \function{sorted()} º¯Êý£¬Ëü²»¸Ä¶¯ÔÐòÁУ¬¶øÊÇÉú³ÉÒ»¸öеÄÅźÃÐòµÄÐòÁС£
1898
1899 \begin{verbatim}
1900 >>> basket = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana']
1901 >>> for f in sorted(set(basket)):
1902 ... print f
1903 ...
1904 apple
1905 banana
1906 orange
1907 pear
1908 \end{verbatim}
1909
1910 \section{More on Conditions ÉîÈëÌõ¼þ¿ØÖÆ\label{conditions}}
1911
1912 The conditions used in \code{while} and \code{if} statements can
1913 contain any operators, not just comparisons.
1914
1915 \code{while} ºÍ \code{if} Óï¾äÖÐʹÓõÄÌõ¼þ²»½ö¿ÉÒÔʹÓñȽϣ¬¶øÇÒ¿ÉÒÔ°üº¬ÈÎÒâµÄ²Ù×÷¡£
1916
1917 The comparison operators \code{in} and \code{not in} check whether a value
1918 occurs (does not occur) in a sequence. The operators \code{is} and
1919 \code{is not} compare whether two objects are really the same object; this
1920 only matters for mutable objects like lists. All comparison operators
1921 have the same priority, which is lower than that of all numerical
1922 operators.
1923
1924 \code{in} ºÍ \code{not in} ±È½Ï²Ù×÷·ûÉóºËÖµÊÇ·ñÔÚÒ»¸öÇø¼äÖ®ÄÚ¡£²Ù×÷·û \code{is} \code{is not} ºÍ±È½ÏÁ½¸ö¶ÔÏóÊÇ·ñÏàͬ£»ÕâÖ»ºÍÖîÈçÁ´±íÕâÑùµÄ¿É±ä¶ÔÏóÓйء£ËùÓеıȽϲÙ×÷·û¾ßÓÐÏàͬµÄÓÅÏȼ¶£¬µÍÓÚËùÓеÄÊýÖµ²Ù×÷¡£
1925
1926 Comparisons can be chained. For example, \code{a < b == c} tests
1927 whether \code{a} is less than \code{b} and moreover \code{b} equals
1928 \code{c}.
1929
1930 ±È½Ï²Ù×÷¿ÉÒÔ´«µÝ¡£ÀýÈç \code{a < b == c} ÉóºËÊÇ·ñ \code{a} СÓÚ \code{b} ²¢ \code{b} µÈÓÚ\code{c}¡£
1931
1932 Comparisons may be combined using the Boolean operators \code{and} and
1933 \code{or}, and the outcome of a comparison (or of any other Boolean
1934 expression) may be negated with \code{not}. These have lower
1935 priorities than comparison operators; between them, \code{not} has
1936 the highest priority and \code{or} the lowest, so that
1937 \code{A and not B or C} is equivalent to \code{(A and (not B)) or C}.
1938 As always, parentheses can be used to express the desired composition.
1939
1940 ±È½Ï²Ù×÷¿ÉÒÔͨ¹ýÂß¼²Ù×÷·û \code{and} ºÍ \code{or} ×éºÏ£¬±È½ÏµÄ½á¹û¿ÉÒÔÓà \code{not} À´È¡·´Òå¡£ÕâЩ²Ù×÷·ûµÄÓÅÏȼ¶ÓÖµÍÓڱȽϲÙ×÷·û£¬ÔÚËüÃÇÖ®ÖУ¬\code{not} ¾ßÓÐ×î¸ßµÄÓÅÏȼ¶£¬ \code{or} ÓÅÏȼ¶×îµÍ£¬ËùÒÔ\code{A and not B or C} µÈÓÚ \code{(A and (not B)) or C}¡£µ±È»£¬±í´ïʽ¿ÉÒÔÓÃÆÚÍûµÄ·½Ê½±íʾ¡£
1941
1942 The Boolean operators \code{and} and \code{or} are so-called
1943 \emph{short-circuit} operators: their arguments are evaluated from
1944 left to right, and evaluation stops as soon as the outcome is
1945 determined. For example, if \code{A} and \code{C} are true but
1946 \code{B} is false, \code{A and B and C} does not evaluate the
1947 expression \code{C}. When used as a general value and not as a
1948 Boolean, the return value of a short-circuit operator is the last
1949 evaluated argument.
1950
1951 Âß¼²Ù×÷·û \code{and} ºÍ \code{or} Ò²³Æ×÷\emph{¶Ì·}²Ù×÷·û£ºËüÃǵIJÎÊý´Ó×óÏòÓÒ½âÎö£¬Ò»µ©½á¹û¿ÉÒÔÈ·¶¨¾ÍÍ£Ö¹¡£ÀýÈ磬Èç¹û \code{A} ºÍ \code{C} ÎªÕæ¶ø \code{B} Ϊ¼Ù£¬ \code{A and B and C} ²»»á½âÎö \code{C}¡£×÷ÓÃÓÚÒ»¸öÆÕͨµÄ·ÇÂ߼ֵʱ£¬¶Ì·²Ù×÷·ûµÄ·µ»ØÖµÍ¨³£ÊÇ×îºóÒ»¸ö±äÁ¿
1952
1953 It is possible to assign the result of a comparison or other Boolean
1954 expression to a variable. For example,
1955
1956 ¿ÉÒ԰ѱȽϻòÆäËüÂß¼±í´ïʽµÄ·µ»ØÖµ¸³¸øÒ»¸ö±äÁ¿£¬ÀýÈ磺
1957
1958 \begin{verbatim}
1959 >>> string1, string2, string3 = '', 'Trondheim', 'Hammer Dance'
1960 >>> non_null = string1 or string2 or string3
1961 >>> non_null
1962 'Trondheim'
1963 \end{verbatim}
1964
1965 Note that in Python, unlike C, assignment cannot occur inside expressions.
1966 C programmers may grumble about this, but it avoids a common class of
1967 problems encountered in C programs: typing \code{=} in an expression when
1968 \code{==} was intended.
1969
1970 ÐèҪעÒâµÄÊÇPythonÓëC²»Í¬£¬ÔÚ±í´ïʽÄÚ²¿²»Äܸ³Öµ¡£C ³ÌÐòÔ±¾³£¶Ô´Ë±§Ô¹£¬²»¹ýËü±ÜÃâÁËÒ»ÀàÔÚ C ³ÌÐòÖÐ˾¿Õ¼û¹ßµÄ´íÎó£ºÏëÒªÔÚ½âÎöʽÖÐʹ \code{==} ʱÎóÓÃÁË \code{=} ²Ù×÷·û¡£
1971
1972 \section{Comparing Sequences and Other Types ²»Í¬ÐòÁÐÀàÐ͵ıȽÏ\label{comparing}}
1973
1974 Sequence objects may be compared to other objects with the same
1975 sequence type. The comparison uses \emph{lexicographical} ordering:
1976 first the first two items are compared, and if they differ this
1977 determines the outcome of the comparison; if they are equal, the next
1978 two items are compared, and so on, until either sequence is exhausted.
1979 If two items to be compared are themselves sequences of the same type,
1980 the lexicographical comparison is carried out recursively. If all
1981 items of two sequences compare equal, the sequences are considered
1982 equal. If one sequence is an initial sub-sequence of the other, the
1983 shorter sequence is the smaller (lesser) one. Lexicographical
1984 ordering for strings uses the \ASCII{} ordering for individual
1985 characters. Some examples of comparisons between sequences of the
1986 same type:
1987
1988 ÐòÁжÔÏó¿ÉÒÔÓëÏàͬÀàÐÍµÄÆäËü¶ÔÏó±È½Ï¡£±È½Ï²Ù×÷°´ \emph{×ÖµäÐò} ½øÐУºÊ×ÏȱȽÏǰÁ½¸öÔªËØ£¬Èç¹û²»Í¬£¬¾Í¾ö¶¨Á˱ȽϵĽá¹û£»Èç¹ûÏàͬ£¬¾Í±È½ÏºóÁ½¸öÔªËØ£¬ÒÀ´ËÀàÍÆ£¬Ö±µ½ËùÓÐÐòÁж¼Íê³É±È½Ï¡£Èç¹ûÁ½¸öÔªËØ±¾Éí¾ÍÊÇͬÑùÀàÐ͵ÄÐòÁУ¬¾ÍµÝ¹é×ÖµäÐò±È½Ï¡£Èç¹ûÁ½¸öÐòÁеÄËùÓÐ×ÓÏî¶¼ÏàµÈ£¬¾ÍÈÏΪÐòÁÐÏàµÈ¡£Èç¹ûÒ»¸öÐòÁÐÊÇÁíÒ»¸öÐòÁеijõʼ×ÓÐòÁУ¬½Ï¶ÌµÄÒ»¸öÐòÁоÍСÓÚÁíÒ»¸ö¡£×Ö·û´®µÄ×ÖµäÐò°´ÕÕµ¥×Ö·ûµÄ \ASCII{} ˳Ðò¡£ÏÂÃæÊÇͬÀàÐÍÐòÁÐÖ®¼ä±È½ÏµÄһЩÀý×Ó£º
1989
1990 \begin{verbatim}
1991 (1, 2, 3) < (1, 2, 4)
1992 [1, 2, 3] < [1, 2, 4]
1993 'ABC' < 'C' < 'Pascal' < 'Python'
1994 (1, 2, 3, 4) < (1, 2, 4)
1995 (1, 2) < (1, 2, -1)
1996 (1, 2, 3) == (1.0, 2.0, 3.0)
1997 (1, 2, ('aa', 'ab')) < (1, 2, ('abc', 'a'), 4)
1998 \end{verbatim}
1999
2000 Note that comparing objects of different types is legal. The outcome
2001 is deterministic but arbitrary: the types are ordered by their name.
2002 Thus, a list is always smaller than a string, a string is always
2003 smaller than a tuple, etc. \footnote{
2004 The rules for comparing objects of different types should
2005 not be relied upon; they may change in a future version of
2006 the language.
2007 } Mixed numeric types are compared according to their numeric value, so
2008 0 equals 0.0, etc.
2009
2010 ÐèҪעÒâµÄÊDz»Í¬ÀàÐ͵ĶÔÏó±È½ÏÊǺϷ¨µÄ¡£Êä³ö½á¹ûÊÇÈ·¶¨¶ø·ÇÈÎÒâµÄ£ºÀàÐͰ´ËüÃǵÄÃû×ÖÅÅÐò¡£Òò¶ø£¬Ò»¸öÁ´±í£¨list£©×ÜÊÇСÓÚÒ»¸ö×Ö·û´®£¨string£©£¬Ò»¸ö×Ö·û´®£¨string£©×ÜÊÇСÓÚÒ»¸öÔª×飨tuple£©µÈµÈ¡£ÊýÖµÀàÐͱȽÏʱ»áͳһËüÃǵÄÊý¾ÝÀàÐÍ£¬ËùÒÔ0µÈÓÚ0.0£¬µÈµÈ¡£\footnote{
2011 ²»Í¬ÀàÐͶÔÏóµÄ±È½Ï¹æÔò²»ÒÀÀµÓÚ´Ë£¬ËüÃÇÓпÉÄÜ»áÔÚPythonÓïÑԵĺó¼Ì°æ±¾Öиı䡣
2012 }
2013
2014 \chapter{Modules Ä£¿é \label{modules}}
2015
2016 If you quit from the Python interpreter and enter it again, the
2017 definitions you have made (functions and variables) are lost.
2018 Therefore, if you want to write a somewhat longer program, you are
2019 better off using a text editor to prepare the input for the interpreter
2020 and running it with that file as input instead. This is known as creating a
2021 \emph{script}. As your program gets longer, you may want to split it
2022 into several files for easier maintenance. You may also want to use a
2023 handy function that you've written in several programs without copying
2024 its definition into each program.
2025
2026 Èç¹ûÄãÍ˳ö Python ½âÊÍÆ÷ÖØÐ½øÈ룬ÒÔǰ´´½¨µÄÒ»Çж¨Ò壨±äÁ¿ºÍº¯Êý£©¾ÍÈ«²¿¶ªÊ§ÁË¡£Òò´Ë£¬Èç¹ûÄãÏëдһЩ³¤¾Ã±£´æµÄ³ÌÐò£¬×îºÃʹÓÃÒ»¸öÎı¾±à¼Æ÷À´±àд³ÌÐò£¬°Ñ±£´æºÃµÄÎļþÊäÈë½âÊÍÆ÷¡£ÎÒÃdzÆÖ®Îª´´½¨Ò»¸ö\emph{½Å±¾}¡£³ÌÐò±äµÃ¸ü³¤Ò»Ð©ÁË£¬Äã¿ÉÄÜΪÁË·½±ãά»¤¶ø°ÑËü·ÖÀë³É¼¸¸öÎļþ¡£ÄãÒ²¿ÉÄÜÏëÒªÔÚ¼¸¸ö³ÌÐòÖж¼Ê¹ÓÃÒ»¸ö³£Óõĺ¯Êý£¬µ«ÊDz»Ïë°ÑËüµÄ¶¨Ò叴֯µ½Ã¿Ò»¸ö³ÌÐòÀï¡£
2027
2028 To support this, Python has a way to put definitions in a file and use
2029 them in a script or in an interactive instance of the interpreter.
2030 Such a file is called a \emph{module}; definitions from a module can be
2031 \emph{imported} into other modules or into the \emph{main} module (the
2032 collection of variables that you have access to in a script
2033 executed at the top level
2034 and in calculator mode).
2035
2036 ΪÁËÂú×ãÕâЩÐèÒª£¬PythonÌṩÁËÒ»¸ö·½·¨¿ÉÒÔ´ÓÎļþÖлñÈ¡¶¨Ò壬Ôڽű¾»òÕß½âÊÍÆ÷µÄÒ»¸ö½»»¥Ê½ÊµÀýÖÐʹÓá£ÕâÑùµÄÎļþ±»³ÆÎª\emph{Ä£¿é}£»Ä£¿éÖе͍Òå¿ÉÒÔ\emph{µ¼Èë}µ½ÁíÒ»¸öÄ£¿é»òÖ÷Ä£¿éÖУ¨Ôڽű¾Ö´ÐÐʱ¿ÉÒÔµ÷ÓõıäÁ¿¼¯Î»ÓÚ×î¸ß¼¶£¬²¢ÇÒ´¦ÓÚ¼ÆËãÆ÷ģʽ£©
2037
2038 A module is a file containing Python definitions and statements. The
2039 file name is the module name with the suffix \file{.py} appended. Within
2040 a module, the module's name (as a string) is available as the value of
2041 the global variable \code{__name__}. For instance, use your favorite text
2042 editor to create a file called \file{fibo.py} in the current directory
2043 with the following contents:
2044
2045 Ä£¿éÊǰü À¨Python ¶¨ÒåºÍÉùÃ÷µÄÎļþ¡£ÎļþÃû¾ÍÊÇÄ£¿éÃû¼ÓÉÏ \file{.py} ºó׺¡£Ä£¿éµÄÄ£¿éÃû£¨×öΪһ¸ö×Ö·û´®£©¿ÉÒÔÓÉÈ«¾Ö±äÁ¿ \code{__name__} µÃµ½¡£ÀýÈ磬Äã¿ÉÒÔÓÃ×Ô¼º¹ßÓõÄÎļþ±à¼Æ÷ÔÚµ±Ç°Ä¿Â¼Ï´´½¨Ò»¸ö½Ð \file{fibo.py} µÄÎļþ£¬Â¼ÈëÈçÏÂÄÚÈÝ£º
2046
2047 \begin{verbatim}
2048 # Fibonacci numbers module
2049
2050 def fib(n): # write Fibonacci series up to n
2051 a, b = 0, 1
2052 while b < n:
2053 print b,
2054 a, b = b, a+b
2055
2056 def fib2(n): # return Fibonacci series up to n
2057 result = []
2058 a, b = 0, 1
2059 while b < n:
2060 result.append(b)
2061 a, b = b, a+b
2062 return result
2063 \end{verbatim}
2064
2065 Now enter the Python interpreter and import this module with the
2066 following command:
2067
2068 ÏÖÔÚ½øÈëPython½âÊÍÆ÷£¬ÓÃÈçÏÂÃüÁîµ¼ÈëÕâ¸öÄ£¿é£º
2069
2070 \begin{verbatim}
2071 >>> import fibo
2072 \end{verbatim}
2073
2074 This does not enter the names of the functions defined in \code{fibo}
2075 directly in the current symbol table; it only enters the module name
2076 \code{fibo} there.
2077 Using the module name you can access the functions:
2078
2079 ÕâÑù×ö²»»áÖ±½Ó°Ñ \code{fibo}Öеĺ¯Êýµ¼È뵱ǰµÄÓïÒå±í£»ËüÖ»ÊÇÒýÈëÁËÄ£¿éÃû \code{fibo}¡£Äã¿ÉÒÔͨ¹ýÄ£¿éÃû°´ÈçÏ·½Ê½·ÃÎÊÕâ¸öº¯Êý£º
2080
2081 \begin{verbatim}
2082 >>> fibo.fib(1000)
2083 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987
2084 >>> fibo.fib2(100)
2085 [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
2086 >>> fibo.__name__
2087 'fibo'
2088 \end{verbatim}
2089
2090 If you intend to use a function often you can assign it to a local name:
2091
2092 Èç¹ûÄãÏëÒªÖ±½Óµ÷Óú¯Êý£¬Í¨³£¿ÉÒÔ¸øËü¸³Ò»¸ö±¾µØÃû³Æ£º
2093
2094 \begin{verbatim}
2095 >>> fib = fibo.fib
2096 >>> fib(500)
2097 1 1 2 3 5 8 13 21 34 55 89 144 233 377
2098 \end{verbatim}
2099
2100
2101 \section{More on Modules ÉîÈëÄ£¿é \label{moreModules}}
2102
2103 A module can contain executable statements as well as function
2104 definitions.
2105 These statements are intended to initialize the module.
2106 They are executed only the
2107 \emph{first} time the module is imported somewhere.\footnote{
2108 In fact function definitions are also `statements' that are
2109 `executed'; the execution enters the function name in the
2110 module's global symbol table.
2111 }
2112
2113 Ä£¿é¿ÉÒÔÏñº¯Êý¶¨ÒåÒ»Ñù°üº¬Ö´ÐÐÓï¾ä¡£ÕâЩÓï¾äͨ³£ÓÃÓÚ³õʼ»¯Ä£¿é¡£ËüÃÇÖ»ÔÚÄ£¿é\emph{µÚÒ»´Î}µ¼ÈëʱִÐÐÒ»´Î¡£\footnote{
2114 ÊÂʵÉϺ¯Êý¶¨Òå¼ÈÊÇ¡°ÉùÃ÷¡±ÓÖÊÇ¡°¿ÉÖ´ÐÐÌ塱£»Ö´ÐÐÌåÓɺ¯ÊýÔÚÄ£¿éÈ«¾ÖÓïÒå±íÖеÄÃüÃûµ¼Èë¡£
2115 }
2116
2117 Each module has its own private symbol table, which is used as the
2118 global symbol table by all functions defined in the module.
2119 Thus, the author of a module can use global variables in the module
2120 without worrying about accidental clashes with a user's global
2121 variables.
2122 ¶ÔÓ¦ÓÚ¶¨ÒåÄ£¿éÖÐËùÓк¯ÊýµÄÈ«¾ÖÓïÒå±í£¬Ã¿Ò»¸öÄ£¿éÓÐ×Ô¼ºµÄ˽ÓÐÓïÒå±í¡£Òò´Ë£¬Ä£¿é×÷Õß¿ÉÒÔÔÚÄ£¿éÖÐʹÓÃһЩȫ¾Ö±äÁ¿£¬²»»áÒòΪÓëÓû§µÄÈ«¾Ö±äÁ¿³åÍ»¶øÒý·¢´íÎó¡£
2123 On the other hand, if you know what you are doing you can touch a
2124 module's global variables with the same notation used to refer to its
2125 functions,
2126 \code{modname.itemname}.
2127 ÁíÒ»·½Ã棬Èç¹ûÄãÈ·¶¨ÄãÐèÒªÕâ¸ö£¬¿ÉÒÔÏñÒýÓÃÄ£¿éÖеĺ¯ÊýÒ»Ñù»ñȡģ¿éÖеÄÈ«¾Ö±äÁ¿£¬ÐÎÈ磺\code{modname.itemname}¡£
2128
2129 Modules can import other modules. It is customary but not required to
2130 place all \keyword{import} statements at the beginning of a module (or
2131 script, for that matter). The imported module names are placed in the
2132 importing module's global symbol table.
2133
2134 Ä£¿é¿ÉÒÔµ¼È루import£©ÆäËüÄ£¿é¡£Ï°¹ßÉÏËùÓÐµÄ \keyword{import} Óï¾ä¶¼·ÅÔÚÄ£¿é£¨»ò½Å±¾£¬µÈµÈ£©µÄ¿ªÍ·£¬µ«Õâ²¢²»ÊDZØÐëµÄ¡£±»µ¼ÈëµÄÄ£¿éÃûÈëÔÚ±¾Ä£¿éµÄÈ«¾ÖÓïÒå±íÖС£
2135
2136 There is a variant of the \keyword{import} statement that imports
2137 names from a module directly into the importing module's symbol
2138 table. For example:
2139
2140 \keyword{import} Óï¾äµÄÒ»¸ö±äÌåÖ±½Ó´Ó±»µ¼ÈëµÄÄ£¿éÖе¼ÈëÃüÃûµ½±¾Ä£¿éµÄÓïÒå±íÖС£ÀýÈ磺
2141
2142 \begin{verbatim}
2143 >>> from fibo import fib, fib2
2144 >>> fib(500)
2145 1 1 2 3 5 8 13 21 34 55 89 144 233 377
2146 \end{verbatim}
2147
2148 This does not introduce the module name from which the imports are taken
2149 in the local symbol table (so in the example, \code{fibo} is not
2150 defined).
2151
2152 ÕâÑù²»»á´Ó¾ÖÓòÓïÒå±íÖе¼ÈëÄ£¿éÃû£¨ÈçÉÏËùʾ£¬ \code{fibo}ûÓж¨Ò壩¡£
2153
2154 There is even a variant to import all names that a module defines:
2155
2156 ÉõÖÁÓÐÖÖ·½Ê½¿ÉÒÔµ¼ÈëÄ£¿éÖеÄËùÓж¨Ò壺
2157
2158 \begin{verbatim}
2159 >>> from fibo import *
2160 >>> fib(500)
2161 1 1 2 3 5 8 13 21 34 55 89 144 233 377
2162 \end{verbatim}
2163
2164 This imports all names except those beginning with an underscore
2165 (\code{_}).
2166
2167 ÕâÑù¿ÉÒÔµ¼ÈëËùÓгýÁËÒÔÏ»®Ïß(\code{_})¿ªÍ·µÄÃüÃû¡£
2168
2169 \subsection{The Module Search Path Ä£¿éËÑË÷·¾¶ \label{searchPath}}
2170
2171 \indexiii{module}{search}{path}
2172 When a module named \module{spam} is imported, the interpreter searches
2173 for a file named \file{spam.py} in the current directory,
2174 and then in the list of directories specified by
2175 the environment variable \envvar{PYTHONPATH}. This has the same syntax as
2176 the shell variable \envvar{PATH}, that is, a list of
2177 directory names. When \envvar{PYTHONPATH} is not set, or when the file
2178 is not found there, the search continues in an installation-dependent
2179 default path; on \UNIX, this is usually \file{.:/usr/local/lib/python}.
2180
2181 µ¼ÈëÒ»¸ö½Ð \module{spam} µÄÄ£¿éʱ£¬½âÊÍÆ÷ÏÈÔÚµ±Ç°Ä¿Â¼ÖÐËÑË÷ÃûΪ \file{spam.py} µÄÎļþ£¬È»ºóÔÚ»·¾³±äÁ¿ \envvar{PYTHONPATH} ±íʾµÄĿ¼ÁбíÖÐËÑË÷£¬È»ºóÊÇ»·¾³±äÁ¿ \envvar{PATH} ÖеÄ·¾¶ÁÐ±í¡£Èç¹û \envvar{PYTHONPATH} ûÓÐÉèÖ㬻òÕßÎļþûÓÐÕÒµ½£¬½ÓÏÂÀ´ËÑË÷°²×°Ä¿Â¼£¬ÔÚ \UNIX ÖУ¬Í¨³£ÊÇ \file{.:/usr/local/lib/python}¡£
2182
2183 Actually, modules are searched in the list of directories given by the
2184 variable \code{sys.path} which is initialized from the directory
2185 containing the input script (or the current directory),
2186 \envvar{PYTHONPATH} and the installation-dependent default. This allows
2187 Python programs that know what they're doing to modify or replace the
2188 module search path. Note that because the directory containing the
2189 script being run is on the search path, it is important that the
2190 script not have the same name as a standard module, or Python will
2191 attempt to load the script as a module when that module is imported.
2192 This will generally be an error. See section~\ref{standardModules},
2193 ``Standard Modules,'' for more information.
2194
2195 ʵ¼ÊÉÏ£¬½âÊÍÆ÷ÓÉ \code{sys.path} ±äÁ¿Ö¸¶¨µÄ·¾¶Ä¿Â¼ËÑË÷Ä£¿é£¬¸Ã±äÁ¿³õʼ»¯Ê±Ä¬Èϰüº¬ÁËÊäÈë½Å±¾£¨»òÕßµ±Ç°Ä¿Â¼£©£¬\envvar{PYTHONPATH} ºÍ°²×°Ä¿Â¼¡£ÕâÑù¾ÍÔÊÐíPython³ÌÐò£¨ÔÎÄÈç´Ë£¬programs£»ÎÒ²ÂÏëÓ¦¸ÃÊÇ¡°programer¡±£¬³ÌÐòÔ±££ÒëÕߣ©Á˽âÈçºÎÐ޸ĻòÌæ»»Ä£¿éËÑË÷Ŀ¼¡£ÐèҪעÒâµÄÊÇÓÉÓÚÕâЩĿ¼Öаüº¬ÓÐËÑË÷·¾¶ÖÐÔËÐеĽű¾£¬ËùÒÔÕâЩ½Å±¾²»Ó¦¸ÃºÍ±ê׼ģ¿éÖØÃû£¬·ñÔòÔÚµ¼ÈëÄ£¿éʱPython»á³¢ÊÔ°ÑÕâЩ½Å±¾µ±×÷Ä£¿éÀ´¼ÓÔØ¡£Õâͨ³£»áÒý·¢Ò»¸ö´íÎó¡£Çë²Î¼û6.2½Ú¡°±ê׼ģ¿é£¨~\ref{standardModules}£©¡±ÒÔÁ˽â¸ü¶àµÄÐÅÏ¢¡£
2196
2197 \subsection{``Compiled'' Python files Python¡°±àÒ롱Îļþ }
2198
2199 As an important speed-up of the start-up time for short programs that
2200 use a lot of standard modules, if a file called \file{spam.pyc} exists
2201 in the directory where \file{spam.py} is found, this is assumed to
2202 contain an already-``byte-compiled'' version of the module \module{spam}.
2203 The modification time of the version of \file{spam.py} used to create
2204 \file{spam.pyc} is recorded in \file{spam.pyc}, and the
2205 \file{.pyc} file is ignored if these don't match.
2206
2207 ¶ÔÓÚÒýÓÃÁË´óÁ¿±ê׼ģ¿éµÄ¶Ì³ÌÐò£¬ÓÐÒ»¸öÌá¸ßÆô¶¯ËٶȵÄÖØÒª·½·¨£¬Èç¹ûÔÚ \file{spam.py} ËùÔÚµÄĿ¼Ï´æÔÚÒ»¸öÃûΪ \file{spam.pyc} µÄÎļþ£¬Ëü»á±»ÊÓΪ \module{spam} Ä£¿éµÄÔ¤¡°±àÒ롱£¨``byte-compiled'' £¬¶þ½øÖƱàÒ룩°æ±¾¡£ÓÃÓÚ´´½¨ \file{spam.pyc} µÄÕâÒ»°æ \file{spam.py} µÄÐÞ¸Äʱ¼ä¼Ç¼ÔÚ \file{spam.pyc} ÎļþÖУ¬Èç¹ûÁ½Õß²»Æ¥Å䣬\file{.pyc} Îļþ¾Í±»ºöÂÔ¡£
2208
2209 Normally, you don't need to do anything to create the
2210 \file{spam.pyc} file. Whenever \file{spam.py} is successfully
2211 compiled, an attempt is made to write the compiled version to
2212 \file{spam.pyc}. It is not an error if this attempt fails; if for any
2213 reason the file is not written completely, the resulting
2214 \file{spam.pyc} file will be recognized as invalid and thus ignored
2215 later. The contents of the \file{spam.pyc} file are platform
2216 independent, so a Python module directory can be shared by machines of
2217 different architectures.
2218
2219 ͨ³£Äã²»ÐèҪΪ´´½¨ \file{spam.pyc} Îļþ×öÈκι¤×÷¡£Ò»µ© \file{spam.py} ³É¹¦±àÒ룬¾Í»áÊÔͼ±àÒë¶ÔÓ¦°æ±¾µÄ \file{spam.pyc}¡£Èç¹ûÓÐÈκÎÔÒòµ¼ÖÂдÈë²»³É¹¦£¬·µ»ØµÄ \file{spam.pyc} Îļþ¾Í»áÊÓΪÎÞЧ£¬Ëæºó¼´±»ºöÂÔ¡£ \file{spam.pyc} ÎļþµÄÄÚÈÝÊÇÆ½Ì¨¶ÀÁ¢µÄ£¬ËùÒÔPythonÄ£¿éĿ¼¿ÉÒÔÔÚ²»Í¬¼Ü¹¹µÄ»úÆ÷Ö®¼ä¹²Ïí¡£
2220
2221 Some tips for experts:
2222
2223 ²¿·Ö¸ß¼¶¼¼ÇÉ£º
2224
2225 \begin{itemize}
2226
2227 \item
2228 When the Python interpreter is invoked with the \programopt{-O} flag,
2229 optimized code is generated and stored in \file{.pyo} files. The
2230 optimizer currently doesn't help much; it only removes
2231 \keyword{assert} statements. When \programopt{-O} is used, \emph{all}
2232 bytecode is optimized; \code{.pyc} files are ignored and \code{.py}
2233 files are compiled to optimized bytecode.
2234
2235 ÒÔ \programopt{-O} ²ÎÊýµ÷ÓÃPython½âÊÍÆ÷ʱ£¬»áÉú³ÉÓÅ»¯´úÂë²¢±£´æÔÚ \file{.pyo} ÎļþÖС£ÏÖÔÚµÄÓÅ»¯Æ÷ûÓÐÌ«¶à°ïÖú£»ËüÖ»ÊÇɾ³ýÁ˶ÏÑÔ£¨\keyword{assert} £©Óï¾ä¡£Ê¹Óà \programopt{-O} ²Î²ÎÊý£¬ËùÓеĴúÂë¶¼»á±»ÓÅ»¯£»\code{.pyc} Îļþ±»ºöÂÔ£¬ \code{.py}Îļþ±»±àÒëΪÓÅ»¯´úÂë¡£
2236
2237 \item
2238 Passing two \programopt{-O} flags to the Python interpreter
2239 (\programopt{-OO}) will cause the bytecode compiler to perform
2240 optimizations that could in some rare cases result in malfunctioning
2241 programs. Currently only \code{__doc__} strings are removed from the
2242 bytecode, resulting in more compact \file{.pyo} files. Since some
2243 programs may rely on having these available, you should only use this
2244 option if you know what you're doing.
2245
2246 ÏòPython½âÊÍÆ÷´«µÝÁ½¸ö \programopt{-O} ²ÎÊý£¨\programopt{-OO}£©»áÖ´ÐÐÍêÈ«ÓÅ»¯µÄ¶þ½øÖÆÓÅ»¯±àÒ룬Õâż¶û»áÉú³É´íÎóµÄ³ÌÐò¡£ÏÖÔÚµÄÓÅ»¯Æ÷£¬Ö»ÊÇ´Ó¶þ½øÖÆ´úÂëÖÐɾ³ýÁË \code{__doc__} ·û´®£¬Éú³É¸üΪ½ô´ÕµÄ \file{.pyo} Îļþ¡£ÒòΪijЩ³ÌÐòÒÀÀµÓÚÕâЩ±äÁ¿µÄ¿ÉÓÃÐÔ£¬ÄãÓ¦¸ÃÖ»ÔÚÈ·¶¨ÎÞÎóµÄ³¡ºÏʹÓÃÕâһѡÏî¡£
2247
2248 \item
2249 A program doesn't run any faster when it is read from a \file{.pyc} or
2250 \file{.pyo} file than when it is read from a \file{.py} file; the only
2251 thing that's faster about \file{.pyc} or \file{.pyo} files is the
2252 speed with which they are loaded.
2253
2254 À´×Ô \file{.pyc} Îļþ»ò \file{.pyo} ÎļþÖеijÌÐò²»»á±ÈÀ´×Ô \file{.py} ÎļþµÄÔËÐиü¿ì£» \file{.pyc} »ò \file{.pyo} ÎļþÖ»ÊÇÔÚËüÃǼÓÔØµÄʱºò¸ü¿ìһЩ¡£
2255
2256 \item
2257 When a script is run by giving its name on the command line, the
2258 bytecode for the script is never written to a \file{.pyc} or
2259 \file{.pyo} file. Thus, the startup time of a script may be reduced
2260 by moving most of its code to a module and having a small bootstrap
2261 script that imports that module. It is also possible to name a
2262 \file{.pyc} or \file{.pyo} file directly on the command line.
2263
2264 ͨ¹ý½Å±¾ÃûÔÚÃüÁîÐÐÔËÐнű¾Ê±£¬²»»á½«Îª¸Ã½Å±¾´´½¨µÄ¶þ½øÖÆ´úÂëдÈë \file{.pyc} »ò\file{.pyo} Îļþ¡£µ±È»£¬°Ñ½Å±¾µÄÖ÷Òª´úÂëÒÆ½øÒ»¸öÄ£¿éÀȻºóÓÃÒ»¸öСµÄÆô¶¯½Å±¾µ¼ÈëÕâ¸öÄ£¿é£¬¾Í¿ÉÒÔÌá¸ß½Å±¾µÄÆô¶¯ËÙ¶È¡£Ò²¿ÉÒÔÖ±½ÓÔÚÃüÁîÐÐÖÐÖ¸¶¨Ò»¸ö \file{.pyc} »ò \file{.pyo} Îļþ¡£
2265
2266 \item
2267 It is possible to have a file called \file{spam.pyc} (or
2268 \file{spam.pyo} when \programopt{-O} is used) without a file
2269 \file{spam.py} for the same module. This can be used to distribute a
2270 library of Python code in a form that is moderately hard to reverse
2271 engineer.
2272
2273 ¶ÔÓÚͬһ¸öÄ£¿é£¨ÕâÀïÖ¸Àý³Ì \file{spam.py} ££ÒëÕߣ©£¬¿ÉÒÔÖ»ÓÐ \file{spam.pyc} Îļþ£¨»òÕß \file{spam.pyc} £¬ÔÚʹÓà \programopt{-O} ²ÎÊýʱ£©¶øÃ»ÓÐ \file{spam.py} Îļþ¡£ÕâÑù¿ÉÒÔ´ò°ü·¢²¼±È½ÏÄÑÓÚÄæÏò¹¤³ÌµÄPython´úÂë¿â¡£
2274
2275 \item
2276 The module \ulink{\module{compileall}}{../lib/module-compileall.html}%
2277 {} \refstmodindex{compileall} can create \file{.pyc} files (or
2278 \file{.pyo} files when \programopt{-O} is used) for all modules in a
2279 directory.
2280
2281 \ulink{\module{compileall}}{../lib/module-compileall.html}%
2282 {} \refstmodindex{compileall} Ä£¿é ¿ÉÒÔΪָ¶¨Ä¿Â¼ÖеÄËùÓÐÄ£¿é´´½¨ \file{.pyc} Îļþ£¨»òÕßʹÓà \file{.pyo} ²ÎÊý´´½¨.pyoÎļþ£©¡£
2283
2284 \end{itemize}
2285
2286
2287 \section{Standard Modules ±ê׼ģ¿é\label{standardModules}}
2288
2289 Python comes with a library of standard modules, described in a separate
2290 document, the \citetitle[../lib/lib.html]{Python Library Reference}
2291 (``Library Reference'' hereafter). Some modules are built into the
2292 interpreter; these provide access to operations that are not part of
2293 the core of the language but are nevertheless built in, either for
2294 efficiency or to provide access to operating system primitives such as
2295 system calls. The set of such modules is a configuration option which
2296 also depends on the underlying platform For example,
2297 the \module{amoeba} module is only provided on systems that somehow
2298 support Amoeba primitives. One particular module deserves some
2299 attention: \ulink{\module{sys}}{../lib/module-sys.html}%
2300 \refstmodindex{sys}, which is built into every
2301 Python interpreter. The variables \code{sys.ps1} and
2302 \code{sys.ps2} define the strings used as primary and secondary
2303 prompts:
2304
2305 Python´øÓÐÒ»¸ö±ê׼ģ¿é¿â£¬²¢·¢²¼ÓжÀÁ¢µÄÎĵµ£¬ÃûΪ \citetitle[../lib/lib.html]{Python ¿â²Î¿¼ÊÖ²á} £¨´Ëºó³ÆÆäΪ¡°¿â²Î¿¼Êֲᡱ£©¡£ÓÐһЩģ¿éÄÚÖÃÓÚ½âÊÍÆ÷Ö®ÖУ¬ÕâЩ²Ù×÷µÄ·ÃÎʽӿڲ»ÊÇÓïÑÔÄں˵ÄÒ»²¿·Ö£¬µ«ÊÇÒѾÄÚÖÃÓÚ½âÊÍÆ÷ÁË¡£Õâ¼ÈÊÇΪÁËÌá¸ßЧÂÊ£¬Ò²ÊÇΪÁ˸øÏµÍ³µ÷ÓõȲÙ×÷ϵͳÔÉú·ÃÎÊÌṩ½Ó¿Ú¡£ÕâÀàÄ£¿é¼¯ºÏÊÇÒ»¸öÒÀÀµÓÚµ×²ãÆ½Ì¨µÄÅäÖÃÑ¡Ïî¡£ÀýÈ磬\module{amoeba} Ä£¿éÖ»Ìṩ¶Ô Amoeba ÔÉúϵͳµÄÖ§³Ö¡£ÓÐÒ»¸ö¾ßÌåµÄÄ£¿éÖµµÃ×¢Ò⣺\ulink{\module{sys}}{../lib/module-sys.html}%
2306 \refstmodindex{sys} £¬Õâ¸öÄ£¿éÄÚÖÃÓÚËùÓеÄPython½âÊÍÆ÷¡£±äÁ¿ \code{sys.ps1} ºÍ \code{sys.ps2}¶¨ÒåÁËÖ÷Ìáʾ·ûºÍ¸±ÖúÌáʾ·û×Ö·û´®£º
2307
2308 \begin{verbatim}
2309 >>> import sys
2310 >>> sys.ps1
2311 '>>> '
2312 >>> sys.ps2
2313 '... '
2314 >>> sys.ps1 = 'C> '
2315 C> print 'Yuck!'
2316 Yuck!
2317 C>
2318
2319 \end{verbatim}
2320
2321 These two variables are only defined if the interpreter is in
2322 interactive mode.
2323
2324 ÕâÁ½¸ö±äÁ¿Ö»ÔÚ½âÊÍÆ÷µÄ½»»¥Ä£Ê½ÏÂÓÐÒâÒå¡£
2325
2326 The variable \code{sys.path} is a list of strings that determines the
2327 interpreter's search path for modules. It is initialized to a default
2328 path taken from the environment variable \envvar{PYTHONPATH}, or from
2329 a built-in default if \envvar{PYTHONPATH} is not set. You can modify
2330 it using standard list operations:
2331
2332 ±äÁ¿ \code{sys.path} ÊǽâÊÍÆ÷Ä£¿éËÑË÷·¾¶µÄ×Ö·û´®ÁÐ±í¡£ËüÓÉ»·¾³±äÁ¿ \envvar{PYTHONPATH} ³õʼ»¯£¬Èç¹ûûÓÐÉ趨 \envvar{PYTHONPATH} £¬¾ÍÓÉÄÚÖõÄĬÈÏÖµ³õʼ»¯¡£Äã¿ÉÒÔÓñê×¼µÄ×Ö·û´®²Ù×÷ÐÞ¸ÄËü£º
2333
2334 \begin{verbatim}
2335 >>> import sys
2336 >>> sys.path.append('/ufs/guido/lib/python')
2337 \end{verbatim}
2338
2339 \section{The \function{dir()} Function \function{dir()} º¯Êý \label{dir}}
2340
2341 The built-in function \function{dir()} is used to find out which names
2342 a module defines. It returns a sorted list of strings:
2343
2344 ÄÚÖú¯Êý \function{dir()} ÓÃÓÚ°´Ä£¿éÃûËÑË÷Ä£¿é¶¨Ò壬Ëü·µ»ØÒ»¸ö×Ö·û´®ÀàÐ͵Ĵ洢ÁÐ±í£º
2345
2346 \begin{verbatim}
2347 >>> import fibo, sys
2348 >>> dir(fibo)
2349 ['__name__', 'fib', 'fib2']
2350 >>> dir(sys)
2351 ['__displayhook__', '__doc__', '__excepthook__', '__name__', '__stderr__',
2352 '__stdin__', '__stdout__', '_getframe', 'api_version', 'argv',
2353 'builtin_module_names', 'byteorder', 'callstats', 'copyright',
2354 'displayhook', 'exc_clear', 'exc_info', 'exc_type', 'excepthook',
2355 'exec_prefix', 'executable', 'exit', 'getdefaultencoding', 'getdlopenflags',
2356 'getrecursionlimit', 'getrefcount', 'hexversion', 'maxint', 'maxunicode',
2357 'meta_path', 'modules', 'path', 'path_hooks', 'path_importer_cache',
2358 'platform', 'prefix', 'ps1', 'ps2', 'setcheckinterval', 'setdlopenflags',
2359 'setprofile', 'setrecursionlimit', 'settrace', 'stderr', 'stdin', 'stdout',
2360 'version', 'version_info', 'warnoptions']
2361 \end{verbatim}
2362
2363 Without arguments, \function{dir()} lists the names you have defined
2364 currently:
2365
2366 ÎÞ²ÎÊýµ÷ÓÃʱ£¬ \function{dir()} º¯Êý·µ»Øµ±Ç°¶¨ÒåµÄÃüÃû£º
2367
2368 \begin{verbatim}
2369 >>> a = [1, 2, 3, 4, 5]
2370 >>> import fibo
2371 >>> fib = fibo.fib
2372 >>> dir()
2373 ['__builtins__', '__doc__', '__file__', '__name__', 'a', 'fib', 'fibo', 'sys']
2374 \end{verbatim}
2375
2376 Note that it lists all types of names: variables, modules, functions, etc.
2377
2378 ×¢Òâ¸ÃÁбíÁгöÁËËùÓÐÀàÐ͵ÄÃû³Æ£º±äÁ¿£¬Ä£¿é£¬º¯Êý£¬µÈµÈ£º
2379
2380 \function{dir()} does not list the names of built-in functions and
2381 variables. If you want a list of those, they are defined in the
2382 standard module \module{__builtin__}\refbimodindex{__builtin__}:
2383
2384 \function{dir()} ²»»áÁгöÄÚÖú¯ÊýºÍ±äÁ¿Ãû¡£Èç¹ûÄãÏëÁгöÕâЩÄÚÈÝ£¬ËüÃÇÔÚ±ê׼ģ¿é \module{__builtin__}\refbimodindex{__builtin__}Öж¨Ò壺
2385
2386 \begin{verbatim}
2387 >>> import __builtin__
2388 >>> dir(__builtin__)
2389 ['ArithmeticError', 'AssertionError', 'AttributeError', 'DeprecationWarning',
2390 'EOFError', 'Ellipsis', 'EnvironmentError', 'Exception', 'False',
2391 'FloatingPointError', 'FutureWarning', 'IOError', 'ImportError',
2392 'IndentationError', 'IndexError', 'KeyError', 'KeyboardInterrupt',
2393 'LookupError', 'MemoryError', 'NameError', 'None', 'NotImplemented',
2394 'NotImplementedError', 'OSError', 'OverflowError',
2395 'PendingDeprecationWarning', 'ReferenceError', 'RuntimeError',
2396 'RuntimeWarning', 'StandardError', 'StopIteration', 'SyntaxError',
2397 'SyntaxWarning', 'SystemError', 'SystemExit', 'TabError', 'True',
2398 'TypeError', 'UnboundLocalError', 'UnicodeDecodeError',
2399 'UnicodeEncodeError', 'UnicodeError', 'UnicodeTranslateError',
2400 'UserWarning', 'ValueError', 'Warning', 'WindowsError',
2401 'ZeroDivisionError', '_', '__debug__', '__doc__', '__import__',
2402 '__name__', 'abs', 'apply', 'basestring', 'bool', 'buffer',
2403 'callable', 'chr', 'classmethod', 'cmp', 'coerce', 'compile',
2404 'complex', 'copyright', 'credits', 'delattr', 'dict', 'dir', 'divmod',
2405 'enumerate', 'eval', 'execfile', 'exit', 'file', 'filter', 'float',
2406 'frozenset', 'getattr', 'globals', 'hasattr', 'hash', 'help', 'hex',
2407 'id', 'input', 'int', 'intern', 'isinstance', 'issubclass', 'iter',
2408 'len', 'license', 'list', 'locals', 'long', 'map', 'max', 'min',
2409 'object', 'oct', 'open', 'ord', 'pow', 'property', 'quit', 'range',
2410 'raw_input', 'reduce', 'reload', 'repr', 'reversed', 'round', 'set',
2411 'setattr', 'slice', 'sorted', 'staticmethod', 'str', 'sum', 'super',
2412 'tuple', 'type', 'unichr', 'unicode', 'vars', 'xrange', 'zip']
2413 \end{verbatim}
2414
2415
2416 \section{Packages °ü \label{packages}}
2417
2418 Packages are a way of structuring Python's module namespace
2419 by using ``dotted module names''. For example, the module name
2420 \module{A.B} designates a submodule named \samp{B} in a package named
2421 \samp{A}. Just like the use of modules saves the authors of different
2422 modules from having to worry about each other's global variable names,
2423 the use of dotted module names saves the authors of multi-module
2424 packages like NumPy or the Python Imaging Library from having to worry
2425 about each other's module names.
2426
2427 °üͨ³£ÊÇʹÓÃÓá°Ô²µãÄ£¿éÃû¡±µÄ½á¹¹»¯Ä£¿éÃüÃû¿Õ¼ä¡£ÀýÈ磬ÃûΪ
2428 \module{A.B} µÄÄ£¿é±íʾÁËÃûΪ \samp{A} µÄ°üÖÐÃûΪ \samp{B}
2429 µÄ×ÓÄ£¿é¡£ÕýÈçͬÓÃÄ£¿éÀ´±£´æ²»Í¬µÄÄ£¿é¼Ü¹¹¿ÉÒÔ±ÜÃâÈ«¾Ö±äÁ¿Ö®¼äµÄÏ໥³åÍ»£¬Ê¹ÓÃÔ²µãÄ£¿éÃû±£´æÏñ
2430 NumPy »ò Python Imaging Library
2431 Ö®ÀàµÄ²»Í¬Àà¿â¼Ü¹¹¿ÉÒÔ±ÜÃâÄ£¿éÖ®¼äµÄÃüÃû³åÍ»¡£
2432
2433 Suppose you want to design a collection of modules (a ``package'') for
2434 the uniform handling of sound files and sound data. There are many
2435 different sound file formats (usually recognized by their extension,
2436 for example: \file{.wav}, \file{.aiff}, \file{.au}), so you may need
2437 to create and maintain a growing collection of modules for the
2438 conversion between the various file formats. There are also many
2439 different operations you might want to perform on sound data (such as
2440 mixing, adding echo, applying an equalizer function, creating an
2441 artificial stereo effect), so in addition you will be writing a
2442 never-ending stream of modules to perform these operations. Here's a
2443 possible structure for your package (expressed in terms of a
2444 hierarchical filesystem):
2445
2446 ¼ÙÉèÄãÏÖÔÚÏëÒªÉè¼ÆÒ»¸öÄ£¿é¼¯£¨Ò»¸ö¡°°ü¡±£©À´Í³Ò»´¦ÀíÉùÒôÎļþºÍÉùÒôÊý¾Ý¡£´æÔÚ¼¸ÖÖ²»Í¬µÄÉùÒô¸ñʽ£¨Í¨³£ÓÉËüÃǵÄÀ©Õ¹ÃûÀ´±êʶ£¬ÀýÈ磺\file{.wav} £¬ \file{.aiff} £¬ \file{.au}) £©£¬ÓÚÊÇ£¬ÎªÁËÔÚ²»Í¬ÀàÐ͵ÄÎļþ¸ñʽ֮¼äת»»£¬ÄãÐèҪά»¤Ò»¸ö²»¶ÏÔö³¤µÄ°ü¼¯ºÏ¡£¿ÉÄÜÄ㻹ÏëÒª¶ÔÉùÒôÊý¾Ý×öºÜ¶à²»Í¬µÄ²Ù×÷£¨ÀýÈç»ìÒô£¬Ìí¼Ó»ØÉù£¬Ó¦ÓÃÆ½ºâ¹¦ÄÜ£¬´´½¨Ò»¸öÈËÔìЧ¹û£©£¬ËùÒÔÄãÒª¼ÓÈëÒ»¸öÎÞÏÞÁ÷Ä£¿éÀ´Ö´ÐÐÕâЩ²Ù×÷¡£ÄãµÄ°ü¿ÉÄÜ»áÊÇÕâ¸öÑù×Ó£¨Í¨¹ý·Ö¼¶µÄÎļþÌåϵÀ´½øÐзÖ×飩£º
2447
2448 \begin{verbatim}
2449 Sound/ Top-level package
2450 __init__.py Initialize the sound package
2451 Formats/ Subpackage for file format conversions
2452 __init__.py
2453 wavread.py
2454 wavwrite.py
2455 aiffread.py
2456 aiffwrite.py
2457 auread.py
2458 auwrite.py
2459 ...
2460 Effects/ Subpackage for sound effects
2461 __init__.py
2462 echo.py
2463 surround.py
2464 reverse.py
2465 ...
2466 Filters/ Subpackage for filters
2467 __init__.py
2468 equalizer.py
2469 vocoder.py
2470 karaoke.py
2471 ...
2472 \end{verbatim}
2473
2474 When importing the package, Python searches through the directories
2475 on \code{sys.path} looking for the package subdirectory.
2476
2477 µ¼ÈëÄ£¿éʱ£¬Pythonͨ¹ý \code{sys.path} ÖеÄĿ¼ÁбíÀ´ËÑË÷´æ·Å°üµÄ×ÓĿ¼¡£
2478
2479 The \file{__init__.py} files are required to make Python treat the
2480 directories as containing packages; this is done to prevent
2481 directories with a common name, such as \samp{string}, from
2482 unintentionally hiding valid modules that occur later on the module
2483 search path. In the simplest case, \file{__init__.py} can just be an
2484 empty file, but it can also execute initialization code for the
2485 package or set the \code{__all__} variable, described later.
2486
2487 ±ØÐëÒªÓÐÒ»¸ö \file{__init__.py} ÎļþµÄ´æÔÚ£¬²ÅÄÜʹPythonÊÓ¸ÃĿ¼Ϊһ¸ö°ü£»ÕâÊÇΪÁË·ÀֹijЩĿ¼ʹÓÃÁË\samp{string} ÕâÑùµÄͨÓÃÃû¶øÎÞÒâÖÐÔÚËæºóµÄÄ£¿éËÑË÷·¾¶Öи²¸ÇÁËÕýÈ·µÄÄ£¿é¡£×î¼òµ¥µÄÇé¿öÏ£¬\file{__init__.py} ¿ÉÒÔÖ»ÊÇÒ»¸ö¿ÕÎļþ£¬²»¹ýËüÒ²¿ÉÄܰüº¬Á˰üµÄ³õʼ»¯´úÂ룬»òÕßÉèÖÃÁË \code{__all__} ±äÁ¿£¬ºóÃæ»áÓÐÏà¹Ø½éÉÜ¡£
2488
2489 Users of the package can import individual modules from the
2490 package, for example:
2491
2492 °üÓû§¿ÉÒÔ´Ó°üÖе¼ÈëºÏ·¨µÄÄ£¿é£¬ÀýÈ磺
2493
2494 \begin{verbatim}
2495 import Sound.Effects.echo
2496 \end{verbatim}
2497
2498 This loads the submodule \module{Sound.Effects.echo}. It must be referenced
2499 with its full name.
2500
2501 ÕâÑù¾Íµ¼ÈëÁË \module{Sound.Effects.echo} ×ÓÄ£¿é¡£Ëü±ØÐèͨ¹ýÍêÕûµÄÃû³ÆÀ´ÒýÓá£
2502
2503 \begin{verbatim}
2504 Sound.Effects.echo.echofilter(input, output, delay=0.7, atten=4)
2505 \end{verbatim}
2506
2507 An alternative way of importing the submodule is:
2508
2509 µ¼Èë°üʱÓÐÒ»¸ö¿ÉÒÔÑ¡ÔñµÄ·½Ê½£º
2510
2511 \begin{verbatim}
2512 from Sound.Effects import echo
2513 \end{verbatim}
2514
2515 This also loads the submodule \module{echo}, and makes it available without
2516 its package prefix, so it can be used as follows:
2517
2518 ÕâÑù¾Í¼ÓÔØÁË \module{echo} ×ÓÄ£¿é£¬²¢ÇÒʹµÃËüÔÚûÓаüǰ׺µÄÇé¿öÏÂÒ²¿ÉÒÔʹÓã¬ËùÒÔËü¿ÉÒÔÈçÏ·½Ê½µ÷Óãº
2519
2520 \begin{verbatim}
2521 echo.echofilter(input, output, delay=0.7, atten=4)
2522 \end{verbatim}
2523
2524 Yet another variation is to import the desired function or variable directly:
2525
2526 »¹ÓÐÁíÒ»ÖÖ±äÌåÓÃÓÚÖ±½Óµ¼È뺯Êý»ò±äÁ¿£º
2527
2528 \begin{verbatim}
2529 from Sound.Effects.echo import echofilter
2530 \end{verbatim}
2531
2532 Again, this loads the submodule \module{echo}, but this makes its function
2533 \function{echofilter()} directly available:
2534
2535 ÕâÑù¾ÍÓÖÒ»´Î¼ÓÔØÁË \module{echo} ×ÓÄ£¿é£¬µ«ÕâÑù¾Í¿ÉÒÔÖ±½Óµ÷ÓÃËüµÄ \function{echofilter()} º¯Êý£º
2536
2537 \begin{verbatim}
2538 echofilter(input, output, delay=0.7, atten=4)
2539 \end{verbatim}
2540
2541 Note that when using \code{from \var{package} import \var{item}}, the
2542 item can be either a submodule (or subpackage) of the package, or some
2543 other name defined in the package, like a function, class or
2544 variable. The \code{import} statement first tests whether the item is
2545 defined in the package; if not, it assumes it is a module and attempts
2546 to load it. If it fails to find it, an
2547 \exception{ImportError} exception is raised.
2548
2549 ÐèҪעÒâµÄÊÇʹÓà \code{from \var{package} import \var{item}} ·½Ê½µ¼Èë°üʱ£¬Õâ¸ö×ÓÏitem£©¼È¿ÉÒÔÊǰüÖеÄÒ»¸ö×ÓÄ£¿é£¨»òÒ»¸ö×Ó°ü£©£¬Ò²¿ÉÒÔÊǰüÖж¨ÒåµÄÆäËüÃüÃû£¬Ïñº¯Êý¡¢Àà»ò±äÁ¿¡£\code{import} Óï¾äÊ×ÏȺ˶ÔÊÇ·ñ°üÖÐÓÐÕâ¸ö×ÓÏÈç¹ûûÓУ¬Ëü¼Ù¶¨ÕâÊÇÒ»¸öÄ£¿é£¬²¢³¢ÊÔ¼ÓÔØËü¡£Èç¹ûûÓÐÕÒµ½Ëü£¬»áÒý·¢Ò»¸ö \exception{ImportError} Òì³£¡£
2550
2551 Contrarily, when using syntax like \code{import
2552 \var{item.subitem.subsubitem}}, each item except for the last must be
2553 a package; the last item can be a module or a package but can't be a
2554 class or function or variable defined in the previous item.
2555
2556 Ïà·´£¬Ê¹ÓÃÀàËÆ\code{import \var{item.subitem.subsubitem}} ÕâÑùµÄÓ﷨ʱ£¬ÕâЩ×ÓÏî±ØÐëÊǰü£¬×îºóµÄ×ÓÏî¿ÉÒÔÊǰü»òÄ£¿é£¬µ«²»ÄÜÊÇÇ°Ãæ×ÓÏîÖж¨ÒåµÄÀà¡¢º¯Êý»ò±äÁ¿¡£
2557
2558 \subsection{Importing * From a Package \label{pkg-import-star}}
2559 %The \code{__all__} Attribute
2560
2561 \ttindex{__all__}
2562 Now what happens when the user writes \code{from Sound.Effects import
2563 *}? Ideally, one would hope that this somehow goes out to the
2564 filesystem, finds which submodules are present in the package, and
2565 imports them all. Unfortunately, this operation does not work very
2566 well on Mac and Windows platforms, where the filesystem does not
2567 always have accurate information about the case of a filename! On
2568 these platforms, there is no guaranteed way to know whether a file
2569 \file{ECHO.PY} should be imported as a module \module{echo},
2570 \module{Echo} or \module{ECHO}. (For example, Windows 95 has the
2571 annoying practice of showing all file names with a capitalized first
2572 letter.) The DOS 8+3 filename restriction adds another interesting
2573 problem for long module names.
2574
2575 ÄÇôµ±Óû§Ð´Ï \code{from Sound.Effects import *} ʱ»á·¢ÉúʲôÊ£¿ÀíÏëÖУ¬×ÜÊÇÏ£ÍûÔÚÎļþϵͳÖÐÕÒ³ö°üÖÐËùÓеÄ×ÓÄ£¿é£¬È»ºóµ¼ÈëËüÃÇ¡£²»ÐÒµÄÊÇ£¬Õâ¸ö²Ù×÷ÔÚ Mac ºÍ Windows ƽ̨ÉϹ¤×÷µÄ²¢²»Ì«ºÃ£¬ÕâЩÎļþϵͳµÄÎļþ´óСд²¢²»Ãô¸Ð£¡ÔÚÕâЩƽ̨ÉÏûÓÐʲô·½·¨¿ÉÒÔÈ·±£Ò»¸ö½Ð\file{ECHO.PY} µÄÎļþÓ¦¸Ãµ¼ÈëΪģ¿é \module{echo} ¡¢ \module{Echo} »ò \module{ECHO} ¡££¨ÀýÈ磬Windows 95ÓÐÒ»¸öÌÖÑáµÄϰ¹ß£¬Ëü»á°ÑËùÓеÄÎļþÃû¶¼ÏÔʾΪÊ××Öĸ´óдµÄ·ç¸ñ¡££©DOS 8+3ÎļþÃûÏÞÖÆÓÖ¸ø³¤ÎļþÃûÄ£¿é´øÀ´ÁËÁíÒ»¸öÓÐȤµÄÎÊÌâ¡£
2576
2577 The only solution is for the package author to provide an explicit
2578 index of the package. The import statement uses the following
2579 convention: if a package's \file{__init__.py} code defines a list
2580 named \code{__all__}, it is taken to be the list of module names that
2581 should be imported when \code{from \var{package} import *} is
2582 encountered. It is up to the package author to keep this list
2583 up-to-date when a new version of the package is released. Package
2584 authors may also decide not to support it, if they don't see a use for
2585 importing * from their package. For example, the file
2586 \file{Sounds/Effects/__init__.py} could contain the following code:
2587
2588 ¶ÔÓÚ°üµÄ×÷ÕßÀ´ËµÎ¨Ò»µÄ½â¾ö·½°¸¾ÍÊǸøÌṩһ¸öÃ÷È·µÄ°üË÷Òý¡£import Óï¾ä°´ÈçÏÂÌõ¼þ½øÐÐת»»£ºÖ´ÐÐ \code{from \var{package} import *} ʱ£¬Èç¹û°üÖÐµÄ \file{__init__.py} ´úÂ붨ÒåÁËÒ»¸öÃûΪ \code{__all__} µÄÁ´±í£¬¾Í»á°´ÕÕÁ´±íÖиø³öµÄÄ£¿éÃû½øÐе¼È롣а汾µÄ°ü·¢²¼Ê±×÷Õß¿ÉÒÔÈÎÒâ¸üÐÂÕâ¸öÁ´±í¡£Èç¹û°ü×÷Õß²»Ïë import * µÄʱºòµ¼ÈëËûÃǵİüÖÐËùÓÐÄ£¿é£¬ÄÇôҲ¿ÉÄÜ»á¾ö¶¨²»Ö§³ÖËü£¨import *£©¡£ÀýÈ磬 \file{Sounds/Effects/__init__.py} Õâ¸öÎļþ¿ÉÄܰüÀ¨ÈçÏ´úÂ룺
2589
2590 \begin{verbatim}
2591 __all__ = ["echo", "surround", "reverse"]
2592 \end{verbatim}
2593
2594 This would mean that \code{from Sound.Effects import *} would
2595 import the three named submodules of the \module{Sound} package.
2596
2597 ÕâÒâζ×Å \code{from Sound.Effects import *} Óï¾ä»á´Ó \module{Sound} °üÖе¼ÈëÒÔÉÏÈý¸öÒÑÃüÃûµÄ×ÓÄ£¿é¡£
2598
2599 If \code{__all__} is not defined, the statement \code{from Sound.Effects
2600 import *} does \emph{not} import all submodules from the package
2601 \module{Sound.Effects} into the current namespace; it only ensures that the
2602 package \module{Sound.Effects} has been imported (possibly running any
2603 initialization code in \file{__init__.py}) and then imports whatever names are
2604 defined in the package. This includes any names defined (and
2605 submodules explicitly loaded) by \file{__init__.py}. It also includes any
2606 submodules of the package that were explicitly loaded by previous
2607 import statements. Consider this code:
2608
2609 Èç¹ûûÓж¨Òå \code{__all__} £¬ \code{from Sound.Effects import *} Óï¾ä²»»á´Ó \module{Sound.Effects} °üÖе¼ÈëËùÓеÄ×ÓÄ£¿é¡£Effects µ¼Èëµ½µ±Ç°µÄÃüÃû¿Õ¼ä£¬Ö»ÄÜÈ·¶¨µÄÊǵ¼ÈëÁË Sound.Effects °ü£¨¿ÉÄÜ»áÔËÐÐ \file{__init__.py} Öеijõʼ»¯´úÂ룩ÒÔ¼°°üÖж¨ÒåµÄËùÓÐÃüÃû»áËæÖ®µ¼Èë¡£ÕâÑù¾Í´Ó \file{__init__.py} Öе¼ÈëÁËÿһ¸öÃüÃû£¨ÒÔ¼°Ã÷È·µ¼ÈëµÄ×ÓÄ£¿é£©¡£Í¬ÑùÒ²°üÀ¨ÁËǰÊöµÄimportÓï¾ä´Ó°üÖÐÃ÷È·µ¼ÈëµÄ×ÓÄ£¿é£¬¿¼ÂÇÒÔÏ´úÂ룺
2610
2611 \begin{verbatim}
2612 import Sound.Effects.echo
2613 import Sound.Effects.surround
2614 from Sound.Effects import *
2615 \end{verbatim}
2616
2617 In this example, the echo and surround modules are imported in the
2618 current namespace because they are defined in the
2619 \module{Sound.Effects} package when the \code{from...import} statement
2620 is executed. (This also works when \code{__all__} is defined.)
2621
2622 ÔÚÕâ¸öÀý×ÓÖУ¬echoºÍsurroundÄ£¿éµ¼ÈëÁ˵±Ç°µÄÃüÃû¿Õ¼ä£¬ÕâÊÇÒòΪִÐÐ \code{from...import} Óï¾äʱËüÃÇÒѾ¶¨ÒåÔÚ \module{Sound.Effects} °üÖÐÁË£¨¶¨ÒåÁË \code{__all__} ʱҲ»áͬÑù¹¤×÷£©¡£
2623
2624 Note that in general the practice of importing \code{*} from a module or
2625 package is frowned upon, since it often causes poorly readable code.
2626 However, it is okay to use it to save typing in interactive sessions,
2627 and certain modules are designed to export only names that follow
2628 certain patterns.
2629
2630 ÐèҪעÒâµÄÊÇϰ¹ßÉϲ»Ö÷ÕÅ´ÓÒ»¸ö°ü»òÄ£¿éÖÐÓà import \code{*} µ¼ÈëËùÓÐÄ£¿é£¬ÒòΪÕâÑùµÄͨ³£Òâζ×ſɶÁÐÔ»áºÜ²î¡£È»¶ø£¬ÔÚ½»»¥»á»°ÖÐÕâÑù×ö¿ÉÒÔ¼õÉÙÊäÈ룬Ïà¶ÔÀ´ËµÈ·¶¨µÄÄ£¿é±»Éè¼Æ³ÉÖ»µ¼³öÈ·¶¨µÄģʽÖÐÃüÃûµÄÄÇÒ»²¿·Ö¡£
2631
2632 Remember, there is nothing wrong with using \code{from Package
2633 import specific_submodule}! In fact, this is the
2634 recommended notation unless the importing module needs to use
2635 submodules with the same name from different packages.
2636
2637 ¼Çס£¬ \code{from Package import specific_submodule} ûÓдíÎó£¡ÊÂʵÉÏ£¬³ý·Çµ¼ÈëµÄÄ£¿éÐèҪʹÓÃÆäËü°üÖеÄͬÃû×ÓÄ£¿é£¬·ñÔòÕâÊÇÊܵ½ÍƼöµÄд·¨¡£
2638
2639 \subsection{Intra-package References ÄÚÖðü£¨Intra-package£©²Î¿¼ }
2640
2641 The submodules often need to refer to each other. For example, the
2642 \module{surround} module might use the \module{echo} module. In fact,
2643 such references
2644 are so common that the \keyword{import} statement first looks in the
2645 containing package before looking in the standard module search path.
2646 Thus, the surround module can simply use \code{import echo} or
2647 \code{from echo import echofilter}. If the imported module is not
2648 found in the current package (the package of which the current module
2649 is a submodule), the \keyword{import} statement looks for a top-level
2650 module with the given name.
2651
2652 ×ÓÄ£¿éÖ®¼ä¾³£ÐèÒª»¥ÏàÒýÓá£ÀýÈ磬\module{surround} Ä£¿é¿ÉÄÜ»áÒýÓà \module{echo} Ä£¿é¡£ÊÂʵÉÏ£¬ÕâÑùµÄÒýÓÃÈç´ËÆÕ±é£¬ÒÔÖÂÓÚ \keyword{import} Óï¾ä»áÏÈËÑË÷°üÄÚ²¿£¬È»ºó²ÅÊDZê׼ģ¿éËÑË÷·¾¶¡£Òò´Ë surround Ä£¿é¿ÉÒÔ¼òµ¥µÄµ÷Óà \code{import echo} »òÕß \code{from echo import echofilter} ¡£Èç¹ûûÓÐÔÚµ±Ç°µÄ°üÖз¢ÏÖÒªµ¼ÈëµÄÄ£¿é£¬\keyword{import} Óï¾ä»áÒÀ¾ÝÖ¸¶¨ÃûѰÕÒÒ»¸ö¶¥¼¶Ä£¿é¡£
2653
2654 When packages are structured into subpackages (as with the
2655 \module{Sound} package in the example), there's no shortcut to refer
2656 to submodules of sibling packages - the full name of the subpackage
2657 must be used. For example, if the module
2658 \module{Sound.Filters.vocoder} needs to use the \module{echo} module
2659 in the \module{Sound.Effects} package, it can use \code{from
2660 Sound.Effects import echo}.
2661
2662 Èç¹û°üÖÐʹÓÃÁË×Ó°ü½á¹¹£¨¾ÍÏñʾÀýÖÐµÄ \module{Sound} °ü£©£¬²»´æÔÚʲô´ÓÁÚ½üµÄ°üÖÐÒýÓÃ×ÓÄ£¿éµÄ±ã½Ý·½·¨££±ØÐëʹÓÃ×Ó°üµÄÈ«Ãû¡£ÀýÈ磬Èç¹û \module{Sound.Filters.vocoder} °üÐèҪʹÓà \module{Sound.Effects} °üÖÐµÄ \module{echosa} Ä£¿é£¬Ëü¿ÉÒÔʹÓà \code{from Sound.Effects import echo} ¡£
2663
2664 \subsection{Packages in Multiple Directories ¶àÖØÂ·¾¶Öеİü}
2665
2666 Packages support one more special attribute, \member{__path__}. This
2667 is initialized to be a list containing the name of the directory
2668 holding the package's \file{__init__.py} before the code in that file
2669 is executed. This variable can be modified; doing so affects future
2670 searches for modules and subpackages contained in the package.
2671
2672 °üÖ§³ÖÒ»¸ö¸üÎªÌØÊâµÄ±äÁ¿£¬ \member{__path__} ¡£ ÔÚ°üµÄ \file{__init__.py} Îļþ´úÂëÖ´ÐÐ֮ǰ£¬¸Ã±äÁ¿³õʼ»¯Ò»¸öĿ¼ÃûÁÐ±í¡£¸Ã±äÁ¿¿ÉÒÔÐ޸ģ¬Ëü×÷ÓÃÓÚ°üÖеÄ×Ó°üºÍÄ£¿éµÄËÑË÷¹¦ÄÜ¡£
2673
2674 While this feature is not often needed, it can be used to extend the
2675 set of modules found in a package.
2676
2677 Õâ¸ö¹¦ÄÜ¿ÉÒÔÓÃÓÚÀ©Õ¹°üÖеÄÄ£¿é¼¯£¬²»¹ýËü²»³£Óá£
2678
2679
2680
2681 \chapter{Input and Output ÊäÈëºÍÊä³ö \label{io}}
2682
2683 There are several ways to present the output of a program; data can be
2684 printed in a human-readable form, or written to a file for future use.
2685 This chapter will discuss some of the possibilities.
2686
2687 Óм¸ÖÖ·½·¨¿ÉÒÔ±íÏÖ³ÌÐòµÄÊä³ö½á¹û£»Êý¾Ý¿ÉÒÔÓÿɶÁµÄ½á¹¹´òÓ¡£¬Ò²¿ÉÒÔдÈëÎļþ¹©ÒÔºóʹÓᣱ¾Õ½«»áÌÖÂÛ¼¸ÖÖ¿ÉÐеÄ×ö·¨¡£
2688
2689 \section{Fancier Output Formatting Éè¼ÆÊä³ö¸ñʽ \label{formatting}}
2690
2691 So far we've encountered two ways of writing values: \emph{expression
2692 statements} and the \keyword{print} statement. (A third way is using
2693 the \method{write()} method of file objects; the standard output file
2694 can be referenced as \code{sys.stdout}. See the Library Reference for
2695 more information on this.)
2696
2697 ÎÒÃÇÓÐÁ½ÖÖ´óÏྶͥµÄÊä³öÖµ·½·¨£º\emph{±í´ïʽÓï¾ä}ºÍ \keyword{print} Óï¾ä¡££¨µÚÈýÖÖ·ÃÇóÊÇʹÓÃÎļþ¶ÔÏóµÄ \method{write()} ·½·¨£¬±ê×¼ÎļþÊä³ö¿ÉÒԲο¼ \code{sys.stdout}¡£ÏêϸÄÚÈݲμû¿â²Î¿¼Êֲᡣ£©
2698
2699 Often you'll want more control over the formatting of your output than
2700 simply printing space-separated values. There are two ways to format
2701 your output; the first way is to do all the string handling yourself;
2702 using string slicing and concatenation operations you can create any
2703 layout you can imagine. The standard module
2704 \module{string}\refstmodindex{string} contains some useful operations
2705 for padding strings to a given column width; these will be discussed
2706 shortly. The second way is to use the \code{\%} operator with a
2707 string as the left argument. The \code{\%} operator interprets the
2708 left argument much like a \cfunction{sprintf()}-style format
2709 string to be applied to the right argument, and returns the string
2710 resulting from this formatting operation.
2711
2712 ¿ÉÄÜÄã¾³£ÏëÒª¶ÔÊä³ö¸ñʽ×öһЩ±È¼òµ¥µÄ´òÓ¡¿Õ¸ñ·Ö¸ô·û¸üΪ¸´ÔӵĿØÖÆ¡£ÓÐÁ½ÖÖ·½·¨¿ÉÒÔ¸ñʽ»¯Êä³ö¡£µÚÒ»ÖÖÊÇÓÉÄãÀ´¿ØÖÆÕû¸ö×Ö·û´®£¬Ê¹ÓÃ×Ö·ûÇиîºÍÁª½Ó²Ù×÷¾Í¿ÉÒÔ´´½¨³öÈκÎÄãÏëÒªµÄÊä³öÐÎʽ¡£±ê׼ģ¿é \module{string}\refstmodindex{string} °üÀ¨ÁËһЩ²Ù×÷£¬½«×Ö·û´®Ìî³äÈë¸ø¶¨ÁÐʱ£¬ÕâЩ²Ù×÷ºÜÓÐÓá£ËæºóÎÒÃÇ»áÌÖÂÛÕⲿ·ÖÄÚÈÝ¡£µÚ¶þÖÖ·½·¨ÊÇʹÓà \code{\%} ²Ù×÷·û£¬ÒÔij¸ö×Ö·û´®×öΪÆä×ó²ÎÊý¡£ \code{\%} ²Ù×÷·û½«×ó²ÎÊý½âÊÍΪÀàËÆÓÚ \cfunction{sprintf()} ·ç¸ñµÄ¸ñʽ×Ö·û´®£¬²¢×÷ÓÃÓÚÓÒ²ÎÊý£¬´Ó¸Ã²Ù×÷Öзµ»Ø¸ñʽ»¯µÄ×Ö·û´®¡£
2713
2714 One question remains, of course: how do you convert values to strings?
2715 Luckily, Python has ways to convert any value to a string: pass it to
2716 the \function{repr()} or \function{str()} functions. Reverse quotes
2717 (\code{``}) are equivalent to \function{repr()}, but they are no
2718 longer used in modern Python code and will likely not be in future
2719 versions of the language.
2720
2721 µ±È»£¬»¹ÓÐÒ»¸öÎÊÌ⣬ÈçºÎ½«£¨²»Í¬µÄ£©Öµ×ª»¯Îª×Ö·û´®£¿ºÜÐÒÔË£¬Python×ÜÊǰÑÈÎÒâÖµ´«Èë \function{repr()} »ò \function{str()} º¯Êý£¬×ªÎª×Ö·û´®¡£·´ÒýºÅ (\code{``})µÈ¼ÛÓÚ\function{repr()}£¬Î´À´°æ±¾µÄPythonÖн«»áÈ¥µôËüÃÇ£¬Õâ¸ö¹¦Äܲ»ÔÙ³öÏÖÓÚÏÖ´úµÄPython´úÂë¡£
2722
2723 The \function{str()} function is meant to return representations of
2724 values which are fairly human-readable, while \function{repr()} is
2725 meant to generate representations which can be read by the interpreter
2726 (or will force a \exception{SyntaxError} if there is not equivalent
2727 syntax). For objects which don't have a particular representation for
2728 human consumption, \function{str()} will return the same value as
2729 \function{repr()}. Many values, such as numbers or structures like
2730 lists and dictionaries, have the same representation using either
2731 function. Strings and floating point numbers, in particular, have two
2732 distinct representations.
2733
2734 º¯Êý \function{str()} ÓÃÓÚ½«Öµ×ª»¯ÎªÊÊÓÚÈËÔĶÁµÄÐÎʽ£¬¶ø \function{repr()} ת»¯Îª¹©½âÊÍÆ÷¶ÁÈ¡µÄÐÎʽ£¨Èç¹ûûÓеȼ۵ÄÓï·¨£¬Ôò»á·¢Éú \exception{SyntaxError} Òì³££© ij¶ÔÏóûÓÐÊÊÓÚÈËÔĶÁµÄ½âÊÍÐÎʽµÄ»°£¬ \function{str()} »á·µ»ØÓë \function{repr()} µÈͬµÄÖµ¡£ºÜ¶àÀàÐÍ£¬ÖîÈçÊýÖµ»òÁ´±í¡¢×ÖµäÕâÑùµÄ½á¹¹£¬Õë¶Ô¸÷º¯Êý¶¼ÓÐ×ÅͳһµÄ½â¶Á·½Ê½¡£×Ö·û´®ºÍ¸¡µãÊý£¬ÓÐ×ŶÀÌØµÄ½â¶Á·½Ê½¡£
2735
2736 Some examples:
2737
2738 ʾÀý£º
2739
2740 \begin{verbatim}
2741 >>> s = 'Hello, world.'
2742 >>> str(s)
2743 'Hello, world.'
2744 >>> repr(s)
2745 "'Hello, world.'"
2746 >>> str(0.1)
2747 '0.1'
2748 >>> repr(0.1)
2749 '0.10000000000000001'
2750 >>> x = 10 * 3.25
2751 >>> y = 200 * 200
2752 >>> s = 'The value of x is ' + repr(x) + ', and y is ' + repr(y) + '...'
2753 >>> print s
2754 The value of x is 32.5, and y is 40000...
2755 >>> # The repr() of a string adds string quotes and backslashes:
2756 ... hello = 'hello, world\n'
2757 >>> hellos = repr(hello)
2758 >>> print hellos
2759 'hello, world\n'
2760 >>> # The argument to repr() may be any Python object:
2761 ... repr((x, y, ('spam', 'eggs')))
2762 "(32.5, 40000, ('spam', 'eggs'))"
2763 >>> # reverse quotes are convenient in interactive sessions:
2764 ... `x, y, ('spam', 'eggs')`
2765 "(32.5, 40000, ('spam', 'eggs'))"
2766 \end{verbatim}
2767
2768 Here are two ways to write a table of squares and cubes:
2769
2770 ÒÔÏÂÁ½ÖÖ·½·¨¿ÉÒÔÊä³öƽ·½ºÍÁ¢·½±í£º
2771
2772 \begin{verbatim}
2773 >>> for x in range(1, 11):
2774 ... print repr(x).rjust(2), repr(x*x).rjust(3),
2775 ... # Note trailing comma on previous line
2776 ... print repr(x*x*x).rjust(4)
2777 ...
2778 1 1 1
2779 2 4 8
2780 3 9 27
2781 4 16 64
2782 5 25 125
2783 6 36 216
2784 7 49 343
2785 8 64 512
2786 9 81 729
2787 10 100 1000
2788 >>> for x in range(1,11):
2789 ... print '%2d %3d %4d' % (x, x*x, x*x*x)
2790 ...
2791 1 1 1
2792 2 4 8
2793 3 9 27
2794 4 16 64
2795 5 25 125
2796 6 36 216
2797 7 49 343
2798 8 64 512
2799 9 81 729
2800 10 100 1000
2801 \end{verbatim}
2802
2803 (Note that one space between each column was added by the way
2804 \keyword{print} works: it always adds spaces between its arguments.)
2805
2806 £¨ÐèҪעÒâµÄÊÇʹÓà \keyword{print} ·½·¨Ê±Ã¿Á½ÁÐÖ®¼äÓÐÒ»¸ö¿Õ¸ñ£ºËü×ÜÊÇÔÚ²ÎÊýÖ®¼ä¼ÓÒ»¸ö¿Õ¸ñ¡££©
2807
2808 This example demonstrates the \method{rjust()} method of string objects,
2809 which right-justifies a string in a field of a given width by padding
2810 it with spaces on the left. There are similar methods
2811 \method{ljust()} and \method{center()}. These
2812 methods do not write anything, they just return a new string. If
2813 the input string is too long, they don't truncate it, but return it
2814 unchanged; this will mess up your column lay-out but that's usually
2815 better than the alternative, which would be lying about a value. (If
2816 you really want truncation you can always add a slice operation, as in
2817 \samp{x.ljust(n)[:n]}.)
2818
2819 ÒÔÉÏÊÇÒ»¸ö \method{rjust()} º¯ÊýµÄÑÝʾ£¬Õâ¸öº¯Êý°Ñ×Ö·û´®Êä³öµ½Ò»ÁУ¬²¢Í¨¹ýÏò×ó²àÌî³ä¿Õ¸ñÀ´Ê¹ÆäÓÒ¶ÔÆë¡£ÀàËÆµÄº¯Êý»¹ÓÐ \method{ljust()} ºÍ \method{center()}¡£ÕâЩº¯ÊýÖ»ÊÇÊä³öеÄ×Ö·û´®£¬²¢²»¸Ä±äʲô¡£Èç¹ûÊä³öµÄ×Ö·û´®Ì«³¤£¬ËüÃÇÒ²²»»á½Ø¶ÏËü£¬¶øÊÇÔÑùÊä³ö£¬Õâ»áʹÄãµÄÊä³ö¸ñʽ±äµÃ»ìÂÒ£¬²»¹ý×ÜÇ¿¹ýÁíÒ»ÖÖÑ¡Ôñ£¨½Ø¶Ï×Ö·û´®£©£¬ÒòΪÄÇÑù»á²úÉú´íÎóµÄÊä³öÖµ¡££¨Èç¹ûÄãȷʵÐèÒª½Ø¶ÏËü£¬¿ÉÒÔʹÓÃÇиî²Ù×÷£¬ÀýÈ磺" \samp{x.ljust(~n)[:n]}¡££©
2820
2821 There is another method, \method{zfill()}, which pads a
2822 numeric string on the left with zeros. It understands about plus and
2823 minus signs:
2824
2825 »¹ÓÐÒ»¸öº¯Êý£¬ \method{zfill()} ËüÓÃÓÚÏòÊýÖµµÄ×Ö·û´®±í´ï×ó²àÌî³ä0¡£¸Ãº¯Êý¿ÉÒÔÕýÈ·Àí½âÕý¸ººÅ£º
2826
2827 \begin{verbatim}
2828 >>> '12'.zfill(5)
2829 '00012'
2830 >>> '-3.14'.zfill(7)
2831 '-003.14'
2832 >>> '3.14159265359'.zfill(5)
2833 '3.14159265359'
2834 \end{verbatim}
2835
2836 Using the \code{\%} operator looks like this:
2837
2838 ¿ÉÒÔÈçÏÂÕâÑùʹÓà \code{\%} ²Ù×÷·û£º
2839
2840 \begin{verbatim}
2841 >>> import math
2842 >>> print 'The value of PI is approximately %5.3f.' % math.pi
2843 The value of PI is approximately 3.142.
2844 \end{verbatim}
2845
2846 If there is more than one format in the string, you need to pass a
2847 tuple as right operand, as in this example:
2848
2849 Èç¹ûÓг¬¹ýÒ»¸öµÄ×Ö·û´®Òª¸ñʽ»¯ÎªÒ»Ì壬¾ÍÐèÒª½«ËüÃÇ´«ÈëÒ»¸öÔª×é×öΪÓÒÖµ£¬ÈçÏÂËùʾ£º
2850
2851 \begin{verbatim}
2852 >>> table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 7678}
2853 >>> for name, phone in table.items():
2854 ... print '%-10s ==> %10d' % (name, phone)
2855 ...
2856 Jack ==> 4098
2857 Dcab ==> 7678
2858 Sjoerd ==> 4127
2859 \end{verbatim}
2860
2861 Most formats work exactly as in C and require that you pass the proper
2862 type; however, if you don't you get an exception, not a core dump.
2863 The \code{\%s} format is more relaxed: if the corresponding argument is
2864 not a string object, it is converted to string using the
2865 \function{str()} built-in function. Using \code{*} to pass the width
2866 or precision in as a separate (integer) argument is supported. The
2867 C formats \code{\%n} and \code{\%p} are not supported.
2868
2869 ´ó¶àÊýÀà C µÄ¸ñʽ»¯²Ù×÷¶¼ÐèÒªÄã´«ÈëÊʵ±µÄÀàÐÍ£¬²»¹ýÈç¹ûÄãûÓж¨ÒåÒì³££¬Ò²²»»áÓÐʲô´ÓÄÚºËÖÐÖ÷¶¯µÄµ¯³öÀ´¡££¨however, if you don't you get an exception, not a core dump£©Ê¹Óà \code{\%s} ¸ñʽ»á¸üÇáËÉЩ£ºÈç¹û¶ÔÓ¦µÄ²ÎÊý²»ÊÇ×Ö·û´®£¬Ëü»áͨ¹ýÄÚÖÃµÄ \function{str()} º¯Êýת»¯Îª×Ö·û´®¡£PythonÖ§³ÖÓà * ×÷Ϊһ¸ö¸ôÀ루ÕûÐ͵쩲ÎÊýÀ´´«µÝ¿í¶È»ò¾«¶È¡£Python ²»Ö§³Ö CµÄ \code{\%n} ºÍ \code{\%p} ²Ù×÷·û¡£
2870
2871 If you have a really long format string that you don't want to split
2872 up, it would be nice if you could reference the variables to be
2873 formatted by name instead of by position. This can be done by using
2874 form \code{\%(name)format}, as shown here:
2875
2876 Èç¹û¿ÉÒÔÖðµãÒýÓÃÒª¸ñʽ»¯µÄ±äÁ¿Ãû£¬¾Í¿ÉÒÔ²úÉú·ûºÏÕæÊµ³¤¶ÈµÄ¸ñʽ»¯×Ö·û´®£¬²»»á²úÉú¼ä¸ô¡£ÕâһЧ¹û¿ÉÒÔͨ¹ýʹÓÃform \code{\%(name)format} ½á¹¹À´ÊµÏÖ£º
2877
2878 \begin{verbatim}
2879 >>> table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 8637678}
2880 >>> print 'Jack: %(Jack)d; Sjoerd: %(Sjoerd)d; Dcab: %(Dcab)d' % table
2881 Jack: 4098; Sjoerd: 4127; Dcab: 8637678
2882 \end{verbatim}
2883
2884 This is particularly useful in combination with the new built-in
2885 \function{vars()} function, which returns a dictionary containing all
2886 local variables.
2887
2888 Õâ¸ö¼¼ÇÉÔÚÓëеÄÄÚÖú¯Êý \function{vars()} ×éºÏʹÓÃʱ·Ç³£ÓÐÓ㬸ú¯Êý·µ»ØÒ»¸ö°üº¬ËùÓоֲ¿±äÁ¿µÄ×ֵ䡣
2889
2890 \section{Reading and Writing Files ¶ÁдÎļþ \label{files}}
2891
2892 % Opening files
2893 \function{open()}\bifuncindex{open} returns a file
2894 object\obindex{file}, and is most commonly used with two arguments:
2895 \samp{open(\var{filename}, \var{mode})}.
2896
2897 \function{open()}\bifuncindex{open} ·µ»ØÒ»¸öÎļþ\obindex{¶ÔÏó}£¬Í¨³£µÄÓ÷¨ÐèÒªÁ½¸ö²ÎÊý£º \samp{open(\var{filename}, \var{mode})}¡£
2898
2899 \begin{verbatim}
2900 >>> f=open('/tmp/workfile', 'w')
2901 >>> print f
2902 <open file '/tmp/workfile', mode 'w' at 80a0960>
2903 \end{verbatim}
2904
2905 The first argument is a string containing the filename. The second
2906 argument is another string containing a few characters describing the
2907 way in which the file will be used. \var{mode} can be \code{'r'} when
2908 the file will only be read, \code{'w'} for only writing (an existing
2909 file with the same name will be erased), and \code{'a'} opens the file
2910 for appending; any data written to the file is automatically added to
2911 the end. \code{'r+'} opens the file for both reading and writing.
2912 The \var{mode} argument is optional; \code{'r'} will be assumed if
2913 it's omitted.
2914
2915 µÚÒ»¸ö²ÎÊýÊÇÒ»¸ö±êʶÎļþÃûµÄ×Ö·û´®¡£µÚ¶þ¸ö²ÎÊýÊÇÓÉÓÐÏÞµÄ×Öĸ×é³ÉµÄ×Ö·û´®£¬ÃèÊöÁËÎļþ½«»á±»ÈçºÎʹÓ᣿ÉÑ¡µÄ\var{ģʽ} ÓУº \code{'r'} £¬´ËÑ¡ÏîʹÎļþÖ»¶Á£» \code{'w'}£¬´ËÑ¡ÏîʹÎļþֻд£¨¶ÔÓÚͬÃûÎļþ£¬¸Ã²Ù×÷ʹÔÓÐÎļþ±»¸²¸Ç£©£» \code{'a'} £¬´ËÑ¡ÏîÒÔ×·¼Ó·½Ê½´ò¿ªÎļþ£» \code{'r+'} £¬´ËÑ¡ÏîÒÔ¶Áд·½Ê½´ò¿ªÎļþ£»Èç¹ûûÓÐÖ¸¶¨£¬Ä¬ÈÏΪ \code{'r'} ģʽ¡£
2916
2917 On Windows and the Macintosh, \code{'b'} appended to the
2918 mode opens the file in binary mode, so there are also modes like
2919 \code{'rb'}, \code{'wb'}, and \code{'r+b'}. Windows makes a
2920 distinction between text and binary files; the end-of-line characters
2921 in text files are automatically altered slightly when data is read or
2922 written. This behind-the-scenes modification to file data is fine for
2923 \ASCII{} text files, but it'll corrupt binary data like that in \file{JPEG} or
2924 \file{EXE} files. Be very careful to use binary mode when reading and
2925 writing such files.
2926
2927 ÔÚWindows ºÍ Macintoshƽ̨ÉÏ£¬ \code{'b'}ģʽÒÔ¶þ½øÖÆ·½Ê½´ò¿ªÎļþ£¬ËùÒÔ¿ÉÄÜ»áÓÐÀàËÆÓÚ \code{'rb'} £¬\code{'wb'} £¬ \code{'r+b'} µÈµÈģʽ×éºÏ¡£Windowsƽ̨ÉÏÎı¾ÎļþÓë¶þ½øÖÆÎļþÊÇÓÐÇø±ðµÄ£¬¶ÁдÎı¾Îļþʱ£¬ÐÐβ»á×Ô¶¯Ìí¼ÓÐнáÊø·û¡£ÕâÖÖºǫ́²Ù×÷·½Ê½¶Ô\ASCII{} Îı¾ÎļþûÓÐʲôÎÊÌ⣬µ«ÊDzÙ×÷ JPEG »ò \file{.EXE}ÕâÑùµÄ¶þ½øÖÆÎļþʱ¾Í»á²úÉúÆÆ»µ¡£ÔÚ²Ù×÷ÕâЩÎļþʱһ¶¨Òª¼ÇµÃÒÔ¶þ½øÖÆÄ£Ê½´ò¿ª¡£
2928
2929 \subsection{Methods of File Objects Îļþ·½·¨¶ÔÏó \label{fileMethods}}
2930
2931 The rest of the examples in this section will assume that a file
2932 object called \code{f} has already been created.
2933
2934 ±¾½ÚÖеÄʾÀý¶¼Ä¬ÈÏÎļþ¶ÔÏó \code{f} ÒѾ´´½¨¡£
2935
2936 To read a file's contents, call \code{f.read(\var{size})}, which reads
2937 some quantity of data and returns it as a string. \var{size} is an
2938 optional numeric argument. When \var{size} is omitted or negative,
2939 the entire contents of the file will be read and returned; it's your
2940 problem if the file is twice as large as your machine's memory.
2941 Otherwise, at most \var{size} bytes are read and returned. If the end
2942 of the file has been reached, \code{f.read()} will return an empty
2943 string (\code {""}).
2944
2945 Òª¶ÁÈ¡ÎļþÄÚÈÝ£¬ÐèÒªµ÷Óà \code{f.read(\var{size})}£¬¸Ã·½·¨¶ÁÈ¡Èô¸ÉÊýÁ¿µÄÊý¾Ý²¢ÒÔ×Ö·û´®ÐÎʽ·µ»ØÆäÄÚÈÝ£¬×Ö·û´®³¤¶ÈΪÊýÖµ\var{size} ËùÖ¸¶¨µÄ´óС¡£Èç¹ûûÓÐÖ¸¶¨ \var{size}»òÕßÖ¸¶¨Îª¸ºÊý£¬¾Í»á¶ÁÈ¡²¢·µ»ØÕû¸öÎļþ¡£µ±Îļþ´óСΪµ±Ç°»úÆ÷ÄÚ´æÁ½±¶Ê±£¬¾Í»á²úÉúÎÊÌâ¡£Õý³£Çé¿öÏ£¬»á¾¡¿ÉÄܰ´±È½Ï´óµÄ\var{size} ¶ÁÈ¡ºÍ·µ»ØÊý¾Ý¡£Èç¹ûµ½ÁËÎļþĩ⣬\code{f.read()}»á·µ»ØÒ»¸ö¿Õ×Ö·û´®£¨\code {""}£©¡£
2946
2947 \begin{verbatim}
2948 >>> f.read()
2949 'This is the entire file.\n'
2950 >>> f.read()
2951 ''
2952 \end{verbatim}
2953
2954 \code{f.readline()} reads a single line from the file; a newline
2955 character (\code{\e n}) is left at the end of the string, and is only
2956 omitted on the last line of the file if the file doesn't end in a
2957 newline. This makes the return value unambiguous; if
2958 \code{f.readline()} returns an empty string, the end of the file has
2959 been reached, while a blank line is represented by \code{'\e n'}, a
2960 string containing only a single newline.
2961
2962 \code{f.readline()}´ÓÎļþÖжÁÈ¡µ¥¶ÀÒ»ÐУ¬×Ö·û´®½áβ»á×Ô¶¯¼ÓÉÏÒ»¸ö»»Ðзû£¬Ö»Óе±Îļþ×îºóÒ»ÐÐûÓÐÒÔ»»Ðзû½áβʱ£¬ÕâÒ»²Ù×÷²Å»á±»ºöÂÔ¡£ÕâÑù·µ»ØÖµ¾Í²»»áÓÐʲô»ìÏý²»Ç壬Èç¹ûÈç¹û \code{f.readline()}·µ»ØÒ»¸ö¿Õ×Ö·û´®£¬ÄǾͱíʾµ½´ïÁËÎļþĩ⣬Èç¹ûÊÇÒ»¸ö¿ÕÐУ¬¾Í»áÃèÊöΪ\code{'\e n\'} £¬Ò»¸öÖ»°üº¬»»ÐзûµÄ×Ö·û´®¡£
2963
2964 \begin{verbatim}
2965 >>> f.readline()
2966 'This is the first line of the file.\n'
2967 >>> f.readline()
2968 'Second line of the file\n'
2969 >>> f.readline()
2970 ''
2971 \end{verbatim}
2972
2973 \code{f.readlines()} returns a list containing all the lines of data
2974 in the file. If given an optional parameter \var{sizehint}, it reads
2975 that many bytes from the file and enough more to complete a line, and
2976 returns the lines from that. This is often used to allow efficient
2977 reading of a large file by lines, but without having to load the
2978 entire file in memory. Only complete lines will be returned.
2979
2980 \code{f.readlines()}·µ»ØÒ»¸öÁÐ±í£¬ÆäÖаüº¬ÁËÎļþÖÐËùÓеÄÊý¾ÝÐС£Èç¹û¸ø¶¨ÁË\var{sizehint}²ÎÊý£¬¾Í»á¶ÁÈë¶àÓÚÒ»ÐеıÈÌØÊý£¬´ÓÖзµ»Ø¶àÐÐÎı¾¡£Õâ¸ö¹¦ÄÜͨ³£ÓÃÓÚ¸ßЧ¶ÁÈ¡´óÐÍÐÐÎļþ£¬±ÜÃâÁ˽«Õû¸öÎļþ¶ÁÈëÄÚ´æ¡£ÕâÖÖ²Ù×÷Ö»·µ»ØÍêÕûµÄÐС£
2981
2982 \begin{verbatim}
2983 >>> f.readlines()
2984 ['This is the first line of the file.\n', 'Second line of the file\n']
2985 \end{verbatim}
2986
2987 An alternate approach to reading lines is to loop over the file object.
2988 This is memory efficient, fast, and leads to simpler code:
2989
2990 ½»»»Í¨µÀ¿ÉÒÔÑ»·¶ÁÈ¡Îļþ¶ÔÏóÖеÄÐС£ÕâÊÇÄÚ´æ²Ù×÷µÄЧÂÊ£¬¿ìËÙ£¬´úÂë¼òµ¥£º
2991
2992 \begin{verbatim}
2993 >>> for line in f:
2994 print line,
2995
2996 This is the first line of the file.
2997 Second line of the file
2998 \end{verbatim}
2999
3000 The alternative approach is simpler but does not provide as fine-grained
3001 control. Since the two approaches manage line buffering differently,
3002 they should not be mixed.
3003
3004 ½»»»Í¨µÀºÜ¼òµ¥£¬µ«ÊDz»ÌṩÍêÕûµÄ¿ØÖÆ¡£ÒòΪÁ½¸öͨµÀ¹ÜÀíÏß»º³å²»Í¬£¬ËüÃDz»ÄÜ»ìºÏ¡£
3005
3006 \code{f.write(\var{string})} writes the contents of \var{string} to
3007 the file, returning \code{None}.
3008
3009 \code{f.write(\var{string})} ½« \var{string} µÄÄÚÈÝдÈëÎļþ£¬·µ»Ø
3010 \code{None} ¡£
3011
3012 \begin{verbatim}
3013 >>> f.write('This is a test\n')
3014 \end{verbatim}
3015
3016 To write something other than a string, it needs to be converted to a
3017 string first:
3018
3019 Èç¹ûÐèҪдÈë×Ö·û´®ÒÔÍâµÄÊý¾Ý£¬¾ÍÒªÏȰÑÕâЩÊý¾Ýת»»Îª×Ö·û´®¡£
3020
3021 \begin{verbatim}
3022 >>> value = ('the answer', 42)
3023 >>> s = str(value)
3024 >>> f.write(s)
3025 \end{verbatim}
3026
3027 \code{f.tell()} returns an integer giving the file object's current
3028 position in the file, measured in bytes from the beginning of the
3029 file. To change the file object's position, use
3030 \samp{f.seek(\var{offset}, \var{from_what})}. The position is
3031 computed from adding \var{offset} to a reference point; the reference
3032 point is selected by the \var{from_what} argument. A
3033 \var{from_what} value of 0 measures from the beginning of the file, 1
3034 uses the current file position, and 2 uses the end of the file as the
3035 reference point. \var{from_what} can be omitted and defaults to 0,
3036 using the beginning of the file as the reference point.
3037
3038 \code{f.tell()}·µ»ØÒ»¸öÕûÊý£¬´ú±íÎļþ¶ÔÏóÔÚÎļþÖеÄÖ¸ÕëλÖ㬸ÃÊýÖµ¼ÆÁ¿ÁË×ÔÎļþ¿ªÍ·µ½Ö¸Õë´¦µÄ±ÈÌØÊý¡£ÐèÒª¸Ä±äÎļþ¶ÔÏóÖ¸Õë»°»°£¬Ê¹ÓÃ\samp{f.seek(\var{offset},\var{from_what})} ¡£Ö¸ÕëÔڸòÙ×÷ÖдÓÖ¸¶¨µÄÒýÓÃλÖÃÒÆ¶¯\var{offset} ±ÈÌØ£¬ÒýÓÃλÖÃÓÉ \var{from_what} ²ÎÊýÖ¸¶¨¡£ \var{from_what}ֵΪ0±íʾ×ÔÎļþÆð³õ´¦¿ªÊ¼£¬1±íʾ×Ôµ±Ç°ÎļþÖ¸ÕëλÖÿªÊ¼£¬2±íʾ×ÔÎļþĩβ¿ªÊ¼¡£ \var{from_what} ¿ÉÒÔºöÂÔ£¬ÆäĬÈÏֵΪÁ㣬´Ëʱ´ÓÎļþÍ·¿ªÊ¼¡£
3039
3040 \begin{verbatim}
3041 >>> f = open('/tmp/workfile', 'r+')
3042 >>> f.write('0123456789abcdef')
3043 >>> f.seek(5) # Go to the 6th byte in the file
3044 >>> f.read(1)
3045 '5'
3046 >>> f.seek(-3, 2) # Go to the 3rd byte before the end
3047 >>> f.read(1)
3048 'd'
3049 \end{verbatim}
3050
3051 When you're done with a file, call \code{f.close()} to close it and
3052 free up any system resources taken up by the open file. After calling
3053 \code{f.close()}, attempts to use the file object will automatically fail.
3054
3055 ÎļþʹÓÃÍêºó£¬µ÷Óà \code{f.close()}¿ÉÒԹرÕÎļþ£¬ÊÍ·Å´ò¿ªÎļþºóÕ¼ÓõÄϵͳ×ÊÔ´¡£µ÷Óà \code{f.close()}Ö®ºó£¬ÔÙµ÷ÓÃÎļþ¶ÔÏó»á×Ô¶¯Òý·¢´íÎó¡£
3056
3057 \begin{verbatim}
3058 >>> f.close()
3059 >>> f.read()
3060 Traceback (most recent call last):
3061 File "<stdin>", line 1, in ?
3062 ValueError: I/O operation on closed file
3063 \end{verbatim}
3064
3065 File objects have some additional methods, such as
3066 \method{isatty()} and \method{truncate()} which are less frequently
3067 used; consult the Library Reference for a complete guide to file
3068 objects.
3069
3070 Îļþ¶ÔÏó»¹ÓÐһЩ²»Ì«³£Óõĸ½¼Ó·½·¨£¬±ÈÈç \method{isatty()} ºÍ\method{truncate()} ÔÚ¿â²Î¿¼ÊÖ²áÖÐÓÐÎļþ¶ÔÏóµÄÍêÕûÖ¸ÄÏ¡£
3071
3072 \subsection{The \module{pickle} Module \module{pickle} Ä£¿é \label{pickle}}
3073 \refstmodindex{pickle}
3074
3075 Strings can easily be written to and read from a file. Numbers take a
3076 bit more effort, since the \method{read()} method only returns
3077 strings, which will have to be passed to a function like
3078 \function{int()}, which takes a string like \code{'123'} and
3079 returns its numeric value 123. However, when you want to save more
3080 complex data types like lists, dictionaries, or class instances,
3081 things get a lot more complicated.
3082
3083 ÎÒÃÇ¿ÉÒÔºÜÈÝÒ׵ĶÁдÎļþÖеÄ×Ö·û´®¡£ÊýÖµ¾ÍÒª¶à·Ñµã¶ùÖÜÕÛ£¬ÒòΪ\method{read()} ·½·¨Ö»»á·µ»Ø×Ö·û´®£¬Ó¦¸Ã½«Æä´«Èë \function{int()}·½·¨ÖУ¬¾Í¿ÉÒÔ½« \code{'123'}ÕâÑùµÄ×Ö·ûתΪ¶ÔÓ¦µÄÊýÖµ123¡£²»¹ý£¬µ±ÄãÐèÒª±£´æ¸üΪ¸´ÔÓµÄÊý¾ÝÀàÐÍ£¬ÀýÈçÁ´±í¡¢×ֵ䣬ÀàµÄʵÀý£¬ÊÂÇé¾Í»á±äµÃ¸ü¸´ÔÓÁË¡£
3084
3085 Rather than have users be constantly writing and debugging code to
3086 save complicated data types, Python provides a standard module called
3087 \ulink{\module{pickle}}{../lib/module-pickle.html}. This is an
3088 amazing module that can take almost
3089 any Python object (even some forms of Python code!), and convert it to
3090 a string representation; this process is called \dfn{pickling}.
3091 Reconstructing the object from the string representation is called
3092 \dfn{unpickling}. Between pickling and unpickling, the string
3093 representing the object may have been stored in a file or data, or
3094 sent over a network connection to some distant machine.
3095
3096 ºÃÔÚÓû§²»±ØÒª·ÇµÃ×Ô¼º±àдºÍµ÷ÊÔ±£´æ¸´ÔÓÊý¾ÝÀàÐ͵ĴúÂë¡£ PythonÌṩÁËÒ»¸öÃûΪ \ulink{\module{pickle}}{../lib/module-pickle.html}µÄ±ê׼ģ¿é¡£ÕâÊÇÒ»¸öÁîÈËÔÞ̾µÄÄ£¿é£¬¼¸ºõ¿ÉÒÔ°ÑÈκΠPython¶ÔÏó £¨ÉõÖÁÊÇһЩ Python ´úÂë¶Î£¡£©±í´ïΪΪ×Ö·û´®£¬ÕâÒ»¹ý³Ì³ÆÖ®Îª\dfn{·â×°} £¨ \dfn{pickling}£©¡£´Ó×Ö·û´®±í´ï³öÖØÐ¹¹Ôì¶ÔÏó³ÆÖ®Îª\dfn{²ð·â}£¨ \dfn{unpickling}£©¡£·âװ״̬ÖеĶÔÏó¿ÉÒÔ´æ´¢ÔÚÎļþ»ò¶ÔÏóÖУ¬Ò²¿ÉÒÔͨ¹ýÍøÂçÔÚÔ¶³ÌµÄ»úÆ÷Ö®¼ä´«Êä¡£
3097
3098 If you have an object \code{x}, and a file object \code{f} that's been
3099 opened for writing, the simplest way to pickle the object takes only
3100 one line of code:
3101
3102 Èç¹ûÄãÓÐÒ»¸ö¶ÔÏó \code{x} £¬Ò»¸öÒÔдģʽ´ò¿ªµÄÎļþ¶ÔÏó \code{f}£¬·â×°¶ÔÏñµÄ×î¼òµ¥µÄ·½·¨Ö»ÐèÒªÒ»ÐдúÂ룺
3103
3104 \begin{verbatim}
3105 pickle.dump(x, f)
3106 \end{verbatim}
3107
3108 To unpickle the object again, if \code{f} is a file object which has
3109 been opened for reading:
3110
3111 Èç¹û \code{f}ÊÇÒ»¸öÒÔ¶Áģʽ´ò¿ªµÄÎļþ¶ÔÏ󣬾ͿÉÒÔ֨װ²ð·âÕâ¸ö¶ÔÏó£º
3112
3113 \begin{verbatim}
3114 x = pickle.load(f)
3115 \end{verbatim}
3116
3117 (There are other variants of this, used when pickling many objects or
3118 when you don't want to write the pickled data to a file; consult the
3119 complete documentation for
3120 \ulink{\module{pickle}}{../lib/module-pickle.html} in the
3121 \citetitle[../lib/]{Python Library Reference}.)
3122
3123 £¨Èç¹û²»Ïë°Ñ·â×°µÄÊý¾ÝдÈëÎļþ£¬ÕâÀﻹÓÐһЩÆäËüµÄ±ä»¯¿ÉÓá£ÍêÕûµÄ\ulink{\module{pickle}}{../lib/module-pickle.html}
3124 ÎĵµÇë¼û\citetitle[../lib/]{Python ¿â²Î¿¼ÊÖ²á}£©¡£
3125
3126 \ulink{\module{pickle}}{../lib/module-pickle.html} is the standard way
3127 to make Python objects which can be stored and reused by other
3128 programs or by a future invocation of the same program; the technical
3129 term for this is a \dfn{persistent} object. Because
3130 \ulink{\module{pickle}}{../lib/module-pickle.html} is so widely used,
3131 many authors who write Python extensions take care to ensure that new
3132 data types such as matrices can be properly pickled and unpickled.
3133
3134 \ulink{\module{pickle}}{../lib/module-pickle.html} ÊÇ´æ´¢ Python ¶ÔÏóÒÔ¹©ÆäËü³ÌÐò»òÆä±¾ÉíÒÔºóµ÷Óõıê×¼·½·¨¡£ÌṩÕâÒ»×é¼¼ÊõµÄÊÇÒ»¸ö³Ö¾Ã»¯¶ÔÏó£¨ \dfn{persistent} object £©¡£ÒòΪ \ulink{\module{pickle}}{../lib/module-pickle.html} µÄÓÃ;ºÜ¹ã·º£¬ºÜ¶à Python À©Õ¹µÄ×÷Õß¶¼·Ç³£×¢ÒâÀàËÆ¾ØÕóÕâÑùµÄÐÂÊý¾ÝÀàÐÍÊÇ·ñÊʺϷâ×°ºÍ²ð·â¡£
3135
3136
3137
3138 \chapter{Errors and Exceptions ´íÎóºÍÒì³£ \label{errors}}
3139
3140 Until now error messages haven't been more than mentioned, but if you
3141 have tried out the examples you have probably seen some. There are
3142 (at least) two distinguishable kinds of errors:
3143 \emph{syntax errors} and \emph{exceptions}.
3144
3145 ÖÁ½ñΪֹ»¹Ã»ÓнøÒ»²½µÄ̸ÂÛ¹ý´íÎóÐÅÏ¢£¬²»¹ýÔÚÄãÒѾÊÔÑé¹ýµÄÄÇЩÀý×ÓÖУ¬¿ÉÄÜÒѾÓöµ½¹ýһЩ¡£Python ÖУ¨ÖÁÉÙ£©ÓÐÁ½ÖÖ´íÎó£ºÓï·¨´íÎóºÍÒì³££¨ \emph{syntax errors}and \emph{exceptions} £©¡£
3146
3147 \section{Syntax Errors Óï·¨´íÎó \label{syntaxErrors}}
3148
3149 Syntax errors, also known as parsing errors, are perhaps the most common
3150 kind of complaint you get while you are still learning Python:
3151
3152 Óï·¨´íÎó£¬Ò²³Æ×÷½âÎö´íÎ󣬿ÉÄÜÊÇѧϰ Python µÄ¹ý³ÌÖÐ×îÈÝÒ×·¸µÄ£º
3153
3154 \begin{verbatim}
3155 >>> while True print 'Hello world'
3156 File "<stdin>", line 1, in ?
3157 while True print 'Hello world'
3158 ^
3159 SyntaxError: invalid syntax
3160 \end{verbatim}
3161
3162 The parser repeats the offending line and displays a little `arrow'
3163 pointing at the earliest point in the line where the error was
3164 detected. The error is caused by (or at least detected at) the token
3165 \emph{preceding} the arrow: in the example, the error is detected at
3166 the keyword \keyword{print}, since a colon (\character{:}) is missing
3167 before it. File name and line number are printed so you know where to
3168 look in case the input came from a script.
3169
3170 ½âÎöÆ÷»áÖØ¸´³ö´íµÄÐУ¬²¢ÔÚÐÐÖÐ×îÔç·¢ÏֵĴíÎóλÖÃÉÏÏÔʾһ¸öС¼ýÍ·¡£´íÎó£¨ÖÁÉÙÊDZ»¼ì²âµ½µÄ£©¾Í·¢ÉúÔÚ¼ýÍ·Ö¸ÏòµÄλÖá£Ê¾ÀýÖеĴíÎó±íÏÖÔڹؼü×Ö\keyword{print} ÉÏ£¬ÒòΪÔÚËü֮ǰÉÙÁËÒ»¸öðºÅ£¨ \character{:}£©¡£Í¬Ê±Ò²»áÏÔʾÎļþÃûºÍÐкţ¬ÕâÑùÄã¾Í¿ÉÒÔÖªµÀ´íÎóÀ´×ÔÄĸö½Å±¾£¬Ê²Ã´Î»Öá£
3171
3172 \section{Exceptions Òì³£ \label{exceptions}}
3173
3174 Even if a statement or expression is syntactically correct, it may
3175 cause an error when an attempt is made to execute it.
3176 Errors detected during execution are called \emph{exceptions} and are
3177 not unconditionally fatal: you will soon learn how to handle them in
3178 Python programs. Most exceptions are not handled by programs,
3179 however, and result in error messages as shown here:
3180
3181 ¼´Ê¹ÊÇÔÚÓï·¨ÉÏÍêÈ«ÕýÈ·µÄÓï¾ä£¬³¢ÊÔÖ´ÐÐËüµÄʱºò£¬Ò²ÓпÉÄܻᷢÉú´íÎó¡£ÔÚ³ÌÐòÔËÐÐÖмì²â³öµÄ´íÎó³ÆÖ®Îª\emph{Òì³£}£¬Ëüͨ³£²»»áµ¼ÖÂÖÂÃüµÄÎÊÌ⣬ÄãºÜ¿ì¾Í»áѧµ½ÈçºÎÔÚ Python ³ÌÐòÖпØÖÆËüÃÇ¡£´ó¶àÊýÒì³£²»»áÓɳÌÐò´¦Àí£¬¶øÊÇÏÔʾһ¸ö´íÎóÐÅÏ¢£º
3182
3183 \begin{verbatim}
3184 >>> 10 * (1/0)
3185 Traceback (most recent call last):
3186 File "<stdin>", line 1, in ?
3187 ZeroDivisionError: integer division or modulo by zero
3188 >>> 4 + spam*3
3189 Traceback (most recent call last):
3190 File "<stdin>", line 1, in ?
3191 NameError: name 'spam' is not defined
3192 >>> '2' + 2
3193 Traceback (most recent call last):
3194 File "<stdin>", line 1, in ?
3195 TypeError: cannot concatenate 'str' and 'int' objects
3196 \end{verbatim}
3197
3198 The last line of the error message indicates what happened.
3199 Exceptions come in different types, and the type is printed as part of
3200 the message: the types in the example are
3201 \exception{ZeroDivisionError}, \exception{NameError} and
3202 \exception{TypeError}.
3203 The string printed as the exception type is the name of the built-in
3204 exception that occurred. This is true for all built-in
3205 exceptions, but need not be true for user-defined exceptions (although
3206 it is a useful convention).
3207 Standard exception names are built-in identifiers (not reserved
3208 keywords).
3209
3210 ´íÎóÐÅÏ¢µÄ×îºóÒ»ÐÐÖ¸³ö·¢ÉúÁËʲô´íÎó¡£Òì³£Ò²Óв»Í¬µÄÀàÐÍ£¬Òì³£ÀàÐÍ×öΪ´íÎóÐÅÏ¢µÄÒ»²¿·ÖÏÔʾ³öÀ´£ºÊ¾ÀýÖеÄÒì³£·Ö±ðΪ \exception{Áã³ý´íÎó£¨ ZeroDivisionError £©} £¬\exception{ÃüÃû´íÎó£¨ NameError£©} ºÍ \exception{ÀàÐÍ´íÎó£¨TypeError£©}¡£´òÓ¡´íÎóÐÅϢʱ£¬Òì³£µÄÀàÐÍ×÷ΪÒì³£µÄÄÚÖÃÃûÏÔʾ¡£¶ÔÓÚËùÓеÄÄÚÖÃÒì³£¶¼ÊÇÈç´Ë£¬²»¹ýÓû§×Ô¶¨ÒåÒì³£¾Í²»Ò»¶¨ÁË£¨¾¡¹ÜÕâÊÇÒ»¸öºÜÓÐÓõÄÔ¼¶¨£©¡£±ê×¼Òì³£ÃûÊÇÄÚÖõıêʶ£¨Ã»Óб£Áô¹Ø¼ü×Ö£©¡£
3211
3212 The rest of the line provides detail based on the type of exception
3213 and what caused it.
3214
3215 ÕâÒ»ÐкóÒ»²¿·ÖÊǹØÓÚ¸ÃÒì³£ÀàÐ͵ÄÏêϸ˵Ã÷£¬ÕâÒâζ×ÅËüµÄÄÚÈÝÒÀÀµÓÚÒì³£ÀàÐÍ¡£
3216
3217 The preceding part of the error message shows the context where the
3218 exception happened, in the form of a stack traceback.
3219 In general it contains a stack traceback listing source lines; however,
3220 it will not display lines read from standard input.
3221
3222 ´íÎóÐÅÏ¢µÄǰ°ë²¿·ÖÒÔ¶ÑÕ»µÄÐÎʽÁгöÒì³£·¢ÉúµÄλÖá£Í¨³£ÔÚ¶ÑÕ»ÖÐÁгöÁËÔ´´úÂëÐУ¬È»¶ø£¬À´×Ô±ê×¼ÊäÈëµÄÔ´Âë²»»áÏÔʾ³öÀ´¡£
3223
3224 The \citetitle[../lib/module-exceptions.html]{Python Library
3225 Reference} lists the built-in exceptions and their meanings.
3226
3227 \citetitle[../lib/module-exceptions.html]{Python ¿â²Î¿¼ÊÖ²á}ÁгöÁËÄÚÖÃÒì³£ºÍËüÃǵĺ¬Òå¡£
3228
3229
3230 \section{Handling Exceptions ´¦ÀíÒì³£ \label{handling}}
3231
3232 It is possible to write programs that handle selected exceptions.
3233 Look at the following example, which asks the user for input until a
3234 valid integer has been entered, but allows the user to interrupt the
3235 program (using \kbd{Control-C} or whatever the operating system
3236 supports); note that a user-generated interruption is signalled by
3237 raising the \exception{KeyboardInterrupt} exception.
3238
3239 ͨ¹ý±à³Ì¿ÉÒÔ´¦ÀíÖ¸¶¨µÄÒì³£¡£ÒÔϵÄÀý×ÓÖØ¸´ÒªÇóÓû§ÊäÈëÒ»¸öÖµ£¬Ö±µ½Óû§ÊäÈëµÄÊÇÒ»¸öºÏ·¨µÄÕûÊýΪֹ¡£²»¹ýÕâ¸ö³ÌÐòÔÊÐíÓû§ÖжϳÌÐò£¨Ê¹ÓÃ\kbd {Control-C} »òÕ߯äËü²Ù×÷ϵͳ֧³ÖµÄ·½·¨£©¡£ÐèҪעÒâµÄÊÇÓû§·¢³öµÄÖжϻáÒý·¢Ò»¸ö\exception{KeyboardInterrupt} Òì³£¡£
3240
3241 \begin{verbatim}
3242 >>> while True:
3243 ... try:
3244 ... x = int(raw_input("Please enter a number: "))
3245 ... break
3246 ... except ValueError:
3247 ... print "Oops! That was no valid number. Try again..."
3248 ...
3249 \end{verbatim}
3250
3251 The \keyword{try} statement works as follows.
3252
3253 \keyword{try} Óï¾ä°´ÈçÏ·½Ê½¹¤×÷£º
3254
3255 \begin{itemize}
3256 \item
3257 First, the \emph{try clause} (the statement(s) between the
3258 \keyword{try} and \keyword{except} keywords) is executed.
3259
3260 Ê×ÏÈ£¬Ö´ÐÐ \emph{try} ×Ӿ䣨ÔÚ \keyword{try} ºÍ \keyword{except}
3261 ¹Ø¼ü×ÖÖ®¼äµÄ²¿·Ö£©¡£
3262
3263 \item
3264 If no exception occurs, the \emph{except\ clause} is skipped and
3265 execution of the \keyword{try} statement is finished.
3266
3267 Èç¹ûûÓÐÒì³£·¢Éú£¬ \emph{except\ ×Ó¾ä} ÔÚ \keyword{try} Óï¾äÖ´ÐÐÍê±Ïºó¾Í±»ºöÂÔÁË¡£
3268
3269 \item
3270 If an exception occurs during execution of the try clause, the rest of
3271 the clause is skipped. Then if its type matches the exception named
3272 after the \keyword{except} keyword, the except clause is executed, and
3273 then execution continues after the \keyword{try} statement.
3274
3275 Èç¹ûÔÚ \keyword{try}
3276 ×Ó¾äÖ´Ðйý³ÌÖз¢ÉúÁËÒì³££¬ÄÇô¸Ã×Ó¾äÆäÓàµÄ²¿·Ö¾Í»á±»ºöÂÔ¡£Èç¹ûÒ쳣ƥÅäÓÚ \keyword{except} ¹Ø¼ü×ÖºóÃæÖ¸¶¨µÄÒì³£ÀàÐÍ£¬¾ÍÖ´ÐжÔÓ¦µÄexcept×Ӿ䣬ºöÂÔtry×Ó¾äµÄÆäËü²¿·Ö¡£È»ºó¼ÌÐøÖ´ÐÐtryÓï¾äÖ®ºóµÄ´úÂë¡£
3277
3278 \item
3279 If an exception occurs which does not match the exception named in the
3280 except clause, it is passed on to outer \keyword{try} statements; if
3281 no handler is found, it is an \emph{unhandled exception} and execution
3282 stops with a message as shown above.
3283
3284 Èç¹û·¢ÉúÁËÒ»¸öÒì³££¬ÔÚ except ×Ó¾äÖÐûÓÐÓë֮ƥÅäµÄ·ÖÖ§£¬Ëü¾Í»á´«µÝµ½ÉÏÒ»¼¶ \keyword{try} Óï¾äÖС£Èç¹û×îÖÕÈÔÕÒ²»µ½¶ÔÓ¦µÄ´¦ÀíÓï¾ä£¬Ëü¾Í³ÉΪһ¸öδ´¦ÀíÒì³££¬ÖÕÖ¹³ÌÐòÔËÐУ¬ÏÔʾÌáʾÐÅÏ¢¡£
3285
3286 \end{itemize}
3287
3288 A \keyword{try} statement may have more than one except clause, to
3289 specify handlers for different exceptions. At most one handler will
3290 be executed. Handlers only handle exceptions that occur in the
3291 corresponding try clause, not in other handlers of the same
3292 \keyword{try} statement. An except clause may name multiple exceptions
3293 as a parenthesized tuple, for example:
3294
3295 Ò»¸ö \keyword{try} Óï¾ä¿ÉÄܰüº¬¶à¸ö except ×Ӿ䣬·Ö±ðÖ¸¶¨´¦Àí²»Í¬µÄÒì³£¡£ÖÁ¶àÖ»»áÓÐÒ»¸ö·ÖÖ§±»Ö´ÐС£Òì³£´¦Àí³ÌÐòÖ»»á´¦Àí¶ÔÓ¦µÄ \keyword{try} ×Ó¾äÖз¢ÉúµÄÒì³££¬ÔÚͬһ¸ö \keyword{try} Óï¾äÖУ¬ÆäËû×Ó¾äÖз¢ÉúµÄÒì³£Ôò²»×÷´¦Àí¡£Ò»¸öexcept×Ó¾ä¿ÉÒÔÔÚÀ¨ºÅÖÐÁгö¶à¸öÒì³£µÄÃû×Ö£¬ÀýÈ磺
3296
3297 \begin{verbatim}
3298 ... except (RuntimeError, TypeError, NameError):
3299 ... pass
3300 \end{verbatim}
3301
3302 The last except clause may omit the exception name(s), to serve as a
3303 wildcard. Use this with extreme caution, since it is easy to mask a
3304 real programming error in this way! It can also be used to print an
3305 error message and then re-raise the exception (allowing a caller to
3306 handle the exception as well):
3307
3308 ×îºóÒ»¸ö except ×Ó¾ä¿ÉÒÔÊ¡ÂÔÒì³£Ãû£¬°ÑËüµ±×öÒ»¸öͨÅäÏîʹÓá£Ò»¶¨ÒªÉ÷ÓÃÕâÖÖ·½·¨£¬ÒòΪËüºÜ¿ÉÄÜ»áÆÁ±ÎµôÕæÕýµÄ³ÌÐò´íÎó£¬Ê¹ÈËÎÞ·¨·¢ÏÖ£¡ËüÒ²¿ÉÒÔÓÃÓÚ´òÓ¡Ò»ÐдíÎóÐÅÏ¢£¬È»ºóÖØÐÂÅ׳öÒì³££¨¿ÉÒÔʹµ÷ÓÃÕ߸üºÃµÄ´¦ÀíÒì³££©¡£
3309
3310 \begin{verbatim}
3311 import sys
3312
3313 try:
3314 f = open('myfile.txt')
3315 s = f.readline()
3316 i = int(s.strip())
3317 except IOError, (errno, strerror):
3318 print "I/O error(%s): %s" % (errno, strerror)
3319 except ValueError:
3320 print "Could not convert data to an integer."
3321 except:
3322 print "Unexpected error:", sys.exc_info()[0]
3323 raise
3324 \end{verbatim}
3325
3326 The \keyword{try} \ldots\ \keyword{except} statement has an optional
3327 \emph{else clause}, which, when present, must follow all except
3328 clauses. It is useful for code that must be executed if the try
3329 clause does not raise an exception. For example:
3330
3331 \keyword{try} \ldots\ \keyword{except} Óï¾ä¿ÉÒÔ´øÓÐÒ»¸ö \emph{else ×Ó¾ä}£¬ ¸Ã×Ó¾äÖ»ÄܳöÏÖÔÚËùÓÐ except ×Ó¾äÖ®ºó¡£µ± try Óï¾äûÓÐÅ׳öÒ쳣ʱ£¬ÐèÒªÖ´ÐÐһЩ´úÂ룬¿ÉÒÔʹÓÃÕâ¸ö×Ӿ䡣ÀýÈ磺
3332
3333 \begin{verbatim}
3334 for arg in sys.argv[1:]:
3335 try:
3336 f = open(arg, 'r')
3337 except IOError:
3338 print 'cannot open', arg
3339 else:
3340 print arg, 'has', len(f.readlines()), 'lines'
3341 f.close()
3342 \end{verbatim}
3343
3344 The use of the \keyword{else} clause is better than adding additional
3345 code to the \keyword{try} clause because it avoids accidentally
3346 catching an exception that wasn't raised by the code being protected
3347 by the \keyword{try} \ldots\ \keyword{except} statement.
3348
3349 ʹÓà \keyword{else} ×Ó¾ä±ÈÔÚ \keyword{try} ×Ó¾äÖи½¼Ó´úÂëÒªºÃ£¬ÒòΪÕâÑù¿ÉÒÔ±ÜÃâ \keyword{try} \ldots\\keyword{except} ÒâÍâµÄ½Ø»ñ±¾À´²»ÊôÓÚËüÃDZ£»¤µÄÄÇЩ´úÂëÅ׳öµÄÒì³£¡£
3350
3351 When an exception occurs, it may have an associated value, also known as
3352 the exception's \emph{argument}.
3353 The presence and type of the argument depend on the exception type.
3354
3355 ·¢ÉúÒ쳣ʱ£¬¿ÉÄÜ»áÓÐÒ»¸ö¸½ÊôÖµ£¬×÷ΪÒì³£µÄ²ÎÊý´æÔÚ¡£Õâ¸ö²ÎÊýÊÇ·ñ´æÔÚ¡¢ÊÇʲôÀàÐÍ£¬ÒÀÀµÓÚÒì³£µÄÀàÐÍ¡£
3356
3357 The except clause may specify a variable after the exception name (or tuple).
3358 The variable is bound to an exception instance with the arguments stored
3359 in \code{instance.args}. For convenience, the exception instance
3360 defines \method{__getitem__} and \method{__str__} so the arguments can
3361 be accessed or printed directly without having to reference \code{.args}.
3362
3363 ÔÚÒì³£Ãû£¨ÁÐ±í£©Ö®ºó£¬Ò²¿ÉÒÔΪ except ×Ó¾äÖ¸¶¨Ò»¸ö±äÁ¿¡£Õâ¸ö±äÁ¿°ó¶¨ÓÚÒ»¸öÒ쳣ʵÀý£¬Ëü´æ´¢ÔÚ \code{instance.args} µÄ²ÎÊýÖС£ÎªÁË·½±ãÆð¼û£¬Ò쳣ʵÀý¶¨ÒåÁË \method{__getitem__} ºÍ \method{__str__}£¬ÕâÑù¾Í¿ÉÒÔÖ±½Ó·ÃÎʹý´òÓ¡²ÎÊý¶ø²»±ØÒýÓà \code{.args}¡£
3364
3365 But use of \code{.args} is discouraged. Instead, the preferred use is to pass
3366 a single argument to an exception (which can be a tuple if multiple arguments
3367 are needed) and have it bound to the \code{message} attribute. One my also
3368 instantiate an exception first before raising it and add any attributes to it
3369 as desired.
3370
3371 ÕâÖÖ×ö·¨²»ÊܹÄÀø¡£Ïà·´£¬¸üºÃµÄ×ö·¨ÊǸøÒì³£´«µÝÒ»¸ö²ÎÊý£¨Èç¹ûÒª´«µÝ¶à¸ö²ÎÊý£¬¿ÉÒÔ´«µÝÒ»¸öÔª×飩£¬°ÑËü°ó¶¨µ½ \code{message} ÊôÐÔ¡£Ò»µ©Òì³£·¢Éú£¬Ëü»áÔÚÅ׳öǰ°ó¶¨ËùÓÐÖ¸¶¨µÄÊôÐÔ¡£
3372
3373 \begin{verbatim}
3374 >>> try:
3375 ... raise Exception('spam', 'eggs')
3376 ... except Exception, inst:
3377 ... print type(inst) # the exception instance
3378 ... print inst.args # arguments stored in .args
3379 ... print inst # __str__ allows args to printed directly
3380 ... x, y = inst # __getitem__ allows args to be unpacked directly
3381 ... print 'x =', x
3382 ... print 'y =', y
3383 ...
3384 <type 'instance'>
3385 ('spam', 'eggs')
3386 ('spam', 'eggs')
3387 x = spam
3388 y = eggs
3389 \end{verbatim}
3390
3391 If an exception has an argument, it is printed as the last part
3392 (`detail') of the message for unhandled exceptions.
3393
3394 ¶ÔÓÚδ´¦ÀíµÄÒì³££¬Èç¹ûËüÓÐÒ»¸ö²ÎÊý£¬ÄÇ×ö¾Í»á×÷Ϊ´íÎóÐÅÏ¢µÄ×îºóÒ»²¿·Ö£¨¡°Ã÷ϸ¡±£©´òÓ¡³öÀ´¡£
3395
3396 Exception handlers don't just handle exceptions if they occur
3397 immediately in the try clause, but also if they occur inside functions
3398 that are called (even indirectly) in the try clause.
3399 For example:
3400
3401 Òì³£´¦Àí¾ä±ú²»Ö¹¿ÉÒÔ´¦ÀíÖ±½Ó·¢ÉúÔÚ try ×Ó¾äÖеÄÒì³££¬¼´Ê¹ÊÇÆäÖУ¨ÉõÖÁÊǼä½Ó£©µ÷Óõĺ¯Êý£¬·¢ÉúÁËÒì³££¬Ò²Ò»Ñù¿ÉÒÔ´¦Àí¡£ÀýÈ磺
3402
3403 \begin{verbatim}
3404 >>> def this_fails():
3405 ... x = 1/0
3406 ...
3407 >>> try:
3408 ... this_fails()
3409 ... except ZeroDivisionError, detail:
3410 ... print 'Handling run-time error:', detail
3411 ...
3412 Handling run-time error: integer division or modulo by zero
3413 \end{verbatim}
3414
3415
3416 \section{Raising Exceptions Å׳öÒì³£ \label{raising}}
3417
3418 The \keyword{raise} statement allows the programmer to force a
3419 specified exception to occur.
3420 For example:
3421
3422 ³ÌÐòÔ±¿ÉÒÔÓà \keyword{raise} Óï¾äÇ¿ÖÆÖ¸¶¨µÄÒì³£·¢Éú¡£ÀýÈ磺
3423
3424 \begin{verbatim}
3425 >>> raise NameError, 'HiThere'
3426 Traceback (most recent call last):
3427 File "<stdin>", line 1, in ?
3428 NameError: HiThere
3429 \end{verbatim}
3430
3431 The first argument to \keyword{raise} names the exception to be
3432 raised. The optional second argument specifies the exception's
3433 argument. Alternatively, the above could be written as
3434 \code{raise NameError('HiThere')}. Either form works fine, but there
3435 seems to be a growing stylistic preference for the latter.
3436
3437 µÚÒ»¸ö²ÎÊýÖ¸¶¨ÁËËùÅ׳öÒì³£µÄÃû³Æ£¬µÚ¶þ¸öÖ¸¶¨ÁËÒì³£µÄ²ÎÊý¡£»¹ÓÐÒ»ÖÖ¿ÉÒÔÌæ´úµÄд·¨ÊÇ \code{raise NameError('HiThere')}¡£Á½ÖÖÐÎʽ¶¼ÄÜÓã¬Ö»²»¹ý¿´ÉÏȥǰһÖÖ·ç¸ñ±ÈºóÒ»ÖÖ¸üºÃ¡£
3438
3439 If you need to determine whether an exception was raised but don't
3440 intend to handle it, a simpler form of the \keyword{raise} statement
3441 allows you to re-raise the exception:
3442
3443 Èç¹ûÄã¾ö¶¨Å׳öÒ»¸öÒì³£¶ø²»´¦ÀíËü£¬ \keyword{raise} Óï¾ä¿ÉÒÔÈÃÄãºÜ¼òµ¥µÄÖØÐÂÅ׳ö¸ÃÒì³£¡£
3444
3445 \begin{verbatim}
3446 >>> try:
3447 ... raise NameError, 'HiThere'
3448 ... except NameError:
3449 ... print 'An exception flew by!'
3450 ... raise
3451 ...
3452 An exception flew by!
3453 Traceback (most recent call last):
3454 File "<stdin>", line 2, in ?
3455 NameError: HiThere
3456 \end{verbatim}
3457
3458
3459 \section{User-defined Exceptions Óû§×Ô¶¨ÒåÒì³£ \label{userExceptions}}
3460
3461 Programs may name their own exceptions by creating a new exception
3462 class. Exceptions should typically be derived from the
3463 \exception{Exception} class, either directly or indirectly. For
3464 example:
3465
3466 ÔÚ³ÌÐòÖпÉÒÔͨ¹ý´´½¨ÐµÄÒì³£ÀàÐÍÀ´ÃüÃû×Ô¼ºµÄÒì³£¡£Òì³£Ààͨ³£Ó¦¸ÃÖ±½Ó»ò¼ä½ÓµÄ´Ó \exception{Exception} ÀàÅÉÉú£¬ÀýÈ磺
3467
3468 \begin{verbatim}
3469 >>> class MyError(Exception):
3470 ... def __init__(self, value):
3471 ... self.value = value
3472 ... def __str__(self):
3473 ... return repr(self.value)
3474 ...
3475 >>> try:
3476 ... raise MyError(2*2)
3477 ... except MyError, e:
3478 ... print 'My exception occurred, value:', e.value
3479 ...
3480 My exception occurred, value: 4
3481 >>> raise MyError, 'oops!'
3482 Traceback (most recent call last):
3483 File "<stdin>", line 1, in ?
3484 __main__.MyError: 'oops!'
3485 \end{verbatim}
3486
3487 In this example, the default \method{__init__} of \class{Exception}
3488 has been overridden. The new behavior simply creates the \var{value}
3489 attribute. This replaces the default behavior of creating the
3490 \var{args} attribute.
3491
3492 ÔÚÕâ¸öÀý×ÓÖУ¬\class{Exception} ĬÈ쵀 \method{__init__} ±»¸²¸Ç¡£Ðµķ½Ê½¼òµ¥µÄ´´½¨ \var{value} ÊôÐÔ¡£Õâ¾ÍÌæ»»ÁËÔÀ´´´½¨ \var{args} ÊôÐԵķ½Ê½¡£
3493
3494 Exception classes can be defined which do anything any other class can
3495 do, but are usually kept simple, often only offering a number of
3496 attributes that allow information about the error to be extracted by
3497 handlers for the exception. When creating a module that can raise
3498 several distinct errors, a common practice is to create a base class
3499 for exceptions defined by that module, and subclass that to create
3500 specific exception classes for different error conditions:
3501
3502 Òì³£ÀàÖпÉÒÔ¶¨ÒåÈÎºÎÆäËüÀàÖпÉÒÔ¶¨ÒåµÄ¶«Î÷£¬µ«ÊÇͨ³£ÎªÁ˱£³Ö¼òµ¥£¬Ö»ÔÚÆäÖмÓÈ뼸¸öÊôÐÔÐÅÏ¢£¬ÒÔ¹©Òì³£´¦Àí¾ä±úÌáÈ¡¡£Èç¹ûÒ»¸öд´½¨µÄÄ£¿éÖÐÐèÒªÅ׳ö¼¸ÖÖ²»Í¬µÄ´íÎóʱ£¬Ò»¸öͨ³£µÄ×÷·¨ÊÇΪ¸ÃÄ£¿é¶¨ÒåÒ»¸öÒì³£»ùÀ࣬ȻºóÕë¶Ô²»Í¬µÄ´íÎóÀàÐÍÅÉÉú³ö¶ÔÓ¦µÄÒì³£×ÓÀà¡£
3503
3504 \begin{verbatim}
3505 class Error(Exception):
3506 """Base class for exceptions in this module."""
3507 pass
3508
3509 class InputError(Error):
3510 """Exception raised for errors in the input.
3511
3512 Attributes:
3513 expression -- input expression in which the error occurred
3514 message -- explanation of the error
3515 """
3516
3517 def __init__(self, expression, message):
3518 self.expression = expression
3519 self.message = message
3520
3521 class TransitionError(Error):
3522 """Raised when an operation attempts a state transition that's not
3523 allowed.
3524
3525 Attributes:
3526 previous -- state at beginning of transition
3527 next -- attempted new state
3528 message -- explanation of why the specific transition is not allowed
3529 """
3530
3531 def __init__(self, previous, next, message):
3532 self.previous = previous
3533 self.next = next
3534 self.message = message
3535 \end{verbatim}
3536
3537 Most exceptions are defined with names that end in ``Error,'' similar
3538 to the naming of the standard exceptions.
3539
3540 Óë±ê×¼Òì³£ÏàËÆ£¬´ó¶àÊýÒì³£µÄÃüÃû¶¼ÒÔ¡°Error¡±½áβ¡£
3541
3542 Many standard modules define their own exceptions to report errors
3543 that may occur in functions they define. More information on classes
3544 is presented in chapter \ref{classes}, ``Classes.''
3545
3546 ºÜ¶à±ê׼ģ¿éÖж¼¶¨ÒåÁË×Ô¼ºµÄÒì³££¬ÓÃÒÔ±¨¸æÔÚËûÃÇËù¶¨ÒåµÄº¯ÊýÖпÉÄÜ·¢ÉúµÄ´íÎó¡£¹ØÓÚÀàµÄ½øÒ»²½ÐÅÏ¢Çë²Î¼ûµÚ 9 Õ \ref{classes}£¬¡°Àࡱ¡£
3547
3548 \section{Defining Clean-up Actions ¶¨ÒåÇåÀíÐÐΪ \label{cleanup}}
3549
3550 The \keyword{try} statement has another optional clause which is
3551 intended to define clean-up actions that must be executed under all
3552 circumstances. For example:
3553
3554 \keyword{try} Óï¾ä»¹ÓÐÁíÒ»¸ö¿ÉÑ¡µÄ×Ӿ䣬ĿµÄÔÚÓÚ¶¨ÒåÔÚÈκÎÇé¿ö϶¼Ò»¶¨ÒªÖ´ÐеŦÄÜ¡£ÀýÈ磺
3555
3556 \begin{verbatim}
3557 >>> try:
3558 ... raise KeyboardInterrupt
3559 ... finally:
3560 ... print 'Goodbye, world!'
3561 ...
3562 Goodbye, world!
3563 Traceback (most recent call last):
3564 File "<stdin>", line 2, in ?
3565 KeyboardInterrupt
3566 \end{verbatim}
3567
3568 A \emph{finally clause} is always executed before leaving the
3569 \keyword{try} statement, whether an exception has occurred or not.
3570 When an exception has occurred in the \keyword{try} clause and has not
3571 been handled by an \keyword{except} clause (or it has occurred in a
3572 \keyword{except} or \keyword{else} clause), it is re-raised after the
3573 \keyword{finally} clause has been executed. The \keyword{finally} clause
3574 is also executed ``on the way out'' when any other clause of the
3575 \keyword{try} statement is left via a \keyword{break}, \keyword{continue}
3576 or \keyword{return} statement. A more complicated example:
3577
3578 ²»¹Ü try ×Ó¾äÖÐÓÐûÓз¢ÉúÒì³££¬ \emph{finally} ×Ó¾äÔÚ³ÌÐòÀ뿪 \keyword{try} ºó¶¼Ò»¶¨»á±»Ö´ÐС£µ± \keyword{try} ×Ó¾äÖз¢ÉúÁËδ±» \keyword{except} ²¶»ñµÄÒì³££¨»òÕßËü·¢ÉúÔÚ \keyword{excepte} »ò \keyword{else} ×Ó¾äÖУ©£¬ÔÚ finally ×Ó¾äÖ´ÐÐÍêºóËü»á±»ÖØÐÂÅ׳ö¡£ \keyword{try} ×Ó¾ä¾ÓÉ \keyword{break}£¬\keyword{continue} »ò \keyword{return} Óï¾äÍ˳öÒ²Ò»Ñù»áÖ´ÐÐ finally ×Ӿ䡣ÒÔÏÂÊÇÒ»¸ö¸ü¸´ÔÓЩµÄÀý×Ó£º
3579
3580 \begin{verbatim}
3581 >>> def divide(x, y):
3582 ... try:
3583 ... result = x / y
3584 ... except ZeroDivisionError:
3585 ... print "division by zero!"
3586 ... else:
3587 ... print "result is", result
3588 ... finally:
3589 ... print "executing finally clause"
3590 ...
3591 >>> divide(2, 1)
3592 result is 2
3593 executing finally clause
3594 >>> divide(2, 0)
3595 division by zero!
3596 executing finally clause
3597 >>> divide("2", "1")
3598 executing finally clause
3599 Traceback (most recent call last):
3600 File "<stdin>", line 1, in ?
3601 File "<stdin>", line 3, in divide
3602 TypeError: unsupported operand type(s) for /: 'str' and 'str'
3603 \end{verbatim}
3604
3605 As you can see, the \keyword{finally} clause is executed in any
3606 event. The \exception{TypeError} raised by dividing two strings
3607 is not handled by the \keyword{except} clause and therefore
3608 re-raised after the \keyword{finally} clauses has been executed.
3609
3610 ÈçÄãËù¼û£¬\keyword(finally) ×Ó¾äÔÚÈκÎÇé¿ö϶¼»áÖ´ÐС£\exception{TypeError}ÔÚÁ½¸ö×Ö·û´®Ïà³ýµÄʱºòÅ׳ö£¬Î´±» \keyword{except} ×Ӿ䲶»ñ£¬Òò´ËÔÚ \keyword{finally} ×Ó¾äÖ´ÐÐÍê±ÏºóÖØÐÂÅ׳ö¡£
3611
3612 In real world applications, the \keyword{finally} clause is useful
3613 for releasing external resources (such as files or network connections),
3614 regardless of whether the use of the resource was successful.
3615
3616 ÔÚʵ¼ÊµÄÓ¦ÓóÌÐòÖУ¬\keyword{finally} ×Ó¾äÓÃÓÚÊÍ·ÅÍⲿ×ÊÔ´£¨ÀýÈçÎļþ»òÍøÂçÁ¬½Ó£©£¬ÎÞÂÛ×ÊÔ´µÄʹÓÃÊÇ·ñ³É¹¦¡£
3617
3618 \section{Predefined Clean-up Actions Ô¤¶¨ÒåÇåÀíÐÐΪ \label{cleanup-with}}
3619
3620 Some objects define standard clean-up actions to be undertaken when
3621 the object is no longer needed, regardless of whether or not the
3622 operation using the object succeeded or failed.
3623 Look at the following example, which tries to open a file and print
3624 its contents to the screen.
3625
3626 ÓÐЩ¶ÔÏó¶¨ÒåÁ˱ê×¼µÄÇåÀíÐÐΪ£¬ÎÞÂÛ¶ÔÏó²Ù×÷ÊÇ·ñ³É¹¦£¬²»ÔÙÐèÒª¸Ã¶ÔÏóµÄʱºò¾Í»áÆð×÷Óá£ÒÔÏÂʾÀý³¢ÊÔ´ò¿ªÎļþ²¢°ÑÄÚÈÝ´òÓ¡µ½ÆÁÄ»ÉÏ¡£
3627
3628 \begin{verbatim}
3629 for line in open("myfile.txt"):
3630 print line
3631 \end{verbatim}
3632
3633 The problem with this code is that it leaves the file open for an
3634 indeterminate amount of time after the code has finished executing.
3635 This is not an issue in simple scripts, but can be a problem for
3636 larger applications. The \keyword{with} statement allows
3637 objects like files to be used in a way that ensures they are
3638 always cleaned up promptly and correctly.
3639
3640 Õâ¶Î´úÂëµÄÎÊÌâÔÚÓÚÔÚ´úÂëÖ´ÐÐÍêºóûÓÐÁ¢¼´¹Ø±Õ´ò¿ªµÄÎļþ¡£ÕâÔÚ¼òµ¥µÄ½Å±¾Àïûʲô£¬µ«ÊÇ´óÐÍÓ¦ÓóÌÐò¾Í»á³öÎÊÌâ¡£\keyword{with} Óï¾äʹµÃÎļþÖ®ÀàµÄ¶ÔÏó¿ÉÒÔÈ·±£×ÜÄܼ°Ê±×¼È·µØ½øÐÐÇåÀí¡£
3641
3642 \begin{verbatim}
3643 with open("myfile.txt") as f:
3644 for line in f:
3645 print line
3646 \end{verbatim}
3647
3648 After the statement is executed, the file \var{f} is always closed,
3649 even if a problem was encountered while processing the lines. Other
3650 objects which provide predefined clean-up actions will indicate
3651 this in their documentation.
3652
3653 Óï¾äÖ´Ðкó£¬Îļþ \var{f} ×ܻᱻ¹Ø±Õ£¬¼´Ê¹ÊÇÔÚ´¦ÀíÎļþÖеÄÊý¾Ýʱ³ö´íÒ²Ò»Ñù¡£ÆäËü¶ÔÏóÊÇ·ñÌṩÁËÔ¤¶¨ÒåµÄÇåÀíÐÐΪҪ²é¿´ËüÃǵÄÎĵµ¡£
3654
3655 \chapter{Classes \label{classes}}
3656
3657 Python's class mechanism adds classes to the language with a minimum
3658 of new syntax and semantics. It is a mixture of the class mechanisms
3659 found in \Cpp{} and Modula-3. As is true for modules, classes in Python
3660 do not put an absolute barrier between definition and user, but rather
3661 rely on the politeness of the user not to ``break into the
3662 definition.'' The most important features of classes are retained
3663 with full power, however: the class inheritance mechanism allows
3664 multiple base classes, a derived class can override any methods of its
3665 base class or classes, and a method can call the method of a base class with the
3666 same name. Objects can contain an arbitrary amount of private data.
3667
3668 Python ÔÚ¾¡¿ÉÄܲ»Ôö¼ÓеÄÓï·¨ºÍÓïÒåµÄÇé¿öϼÓÈëÁËÀà»úÖÆ¡£ÕâÖÖ»úÖÆÊÇ C++ ºÍ Modula-3 µÄ»ìºÏ¡£PythonÖеÄÀàûÓÐÔÚÓû§ºÍ¶¨ÒåÖ®¼ä½¨Á¢Ò»¸ö¾ø¶ÔµÄÆÁÕÏ£¬¶øÊÇÒÀÀµÓÚÓû§×Ô¾õµÄ²»È¥¡°ÆÆ»µ¶¨Ò塱¡£È»¶ø£¬Àà»úÖÆ×îÖØÒªµÄ¹¦Äܶ¼ÍêÕûµÄ±£ÁôÏÂÀ´¡£Àà¼Ì³Ð»úÖÆÔÊÐí¶à¼Ì³Ð£¬ÅÉÉúÀà¿ÉÒÔ¸²¸Ç£¨override£©»ùÀàÖеÄÈκη½·¨£¬·½·¨ÖпÉÒÔµ÷ÓûùÀàÖеÄͬÃû·½·¨¡£¶ÔÏó¿ÉÒÔ°üº¬ÈÎÒâÊýÁ¿µÄ˽ÓгÉÔ±¡£
3669
3670 In \Cpp{} terminology, all class members (including the data members) are
3671 \emph{public}, and all member functions are \emph{virtual}. There are
3672 no special constructors or destructors. As in Modula-3, there are no
3673 shorthands for referencing the object's members from its methods: the
3674 method function is declared with an explicit first argument
3675 representing the object, which is provided implicitly by the call. As
3676 in Smalltalk, classes themselves are objects, albeit in the wider
3677 sense of the word: in Python, all data types are objects. This
3678 provides semantics for importing and renaming. Unlike
3679 \Cpp{} and Modula-3, built-in types can be used as base classes for
3680 extension by the user. Also, like in \Cpp{} but unlike in Modula-3, most
3681 built-in operators with special syntax (arithmetic operators,
3682 subscripting etc.) can be redefined for class instances.
3683
3684 Óà \Cpp{} ÊõÓïÀ´½²£¬ËùÓеÄÀà³ÉÔ±£¨°üÀ¨Êý¾Ý³ÉÔ±£©¶¼Êǹ«ÓУ¨ \emph{public} £©µÄ£¬ËùÓеijÉÔ±º¯Êý¶¼ÊÇÐéÄ⣨ \emph{virtual} £©µÄ¡£Ã»ÓÐÌØ¶¨µÄ¹¹ÔìºÍÎö¹¹º¯Êý¡£ÓÃModula-3µÄÊõÓïÀ´½²£¬ÔÚ³ÉÔ±·½·¨ÖÐûÓÐʲô¼ò±ãµÄ·½Ê½£¨shorthands£©¿ÉÒÔÒýÓöÔÏóµÄ³ÉÔ±£º·½·¨º¯ÊýÔÚ¶¨ÒåʱÐèÒªÒÔÒýÓõĶÔÏó×öΪµÚÒ»¸ö²ÎÊý£¬µ÷ÓÃʱÔò»áÒþʽÒýÓöÔÏó¡£ÕâÑù¾ÍÐγÉÁËÓïÒåÉϵÄÒýÈëºÍÖØÃüÃû¡££¨ This provides semantics for importing and renaming. £©µ«ÊÇ£¬Ïñ \Cpp{} ¶ø·Ç Modula-3 ÖÐÄÇÑù£¬´ó¶àÊý´øÓÐÌØÊâÓï·¨µÄÄÚÖòÙ×÷·û£¨Ëã·¨ÔËËã·û¡¢Ï±êµÈ£©¶¼¿ÉÒÔÕë¶ÔÀàµÄÐèÒªÖØÐ¶¨Òå¡£
3685
3686 \section{A Word About Terminology ÊõÓïÂþ̸ \label{terminology}}
3687
3688 Lacking universally accepted terminology to talk about classes, I will
3689 make occasional use of Smalltalk and \Cpp{} terms. (I would use Modula-3
3690 terms, since its object-oriented semantics are closer to those of
3691 Python than \Cpp, but I expect that few readers have heard of it.)
3692
3693 ÓÉÓÚûÓÐʲô¹ØÓÚÀàµÄͨÓÃÊõÓÎÒ´Ó Smalltalk ºÍ C++ ÖнèÓÃһЩ£¨ÎÒ¸üÏ£ÍûÓà Modula-3 µÄ£¬ÒòΪËüµÄÃæÏò¶ÔÏó»úÖÆ±È \Cpp ¸ü½Ó½üPython£¬²»¹ýÎÒÏëû¶àÉÙ¶ÁÕßÌý˵¹ýËü£©¡£
3694
3695 Objects have individuality, and multiple names (in multiple scopes)
3696 can be bound to the same object. This is known as aliasing in other
3697 languages. This is usually not appreciated on a first glance at
3698 Python, and can be safely ignored when dealing with immutable basic
3699 types (numbers, strings, tuples). However, aliasing has an
3700 (intended!) effect on the semantics of Python code involving mutable
3701 objects such as lists, dictionaries, and most types representing
3702 entities outside the program (files, windows, etc.). This is usually
3703 used to the benefit of the program, since aliases behave like pointers
3704 in some respects. For example, passing an object is cheap since only
3705 a pointer is passed by the implementation; and if a function modifies
3706 an object passed as an argument, the caller will see the change --- this
3707 eliminates the need for two different argument passing mechanisms as in
3708 Pascal.
3709
3710 ¶ÔÏóÊDZ»ÌØ»¯µÄ£¬¶à¸öÃû×Ö£¨ÔÚ¶à¸ö×÷ÓÃÓòÖУ©¿ÉÒÔ°ó¶¨Í¬Ò»¸ö¶ÔÏó¡£ÕâÏ൱ÓÚÆäËüÓïÑÔÖеıðÃû¡£Í¨³£¶Ô Python µÄµÚÒ»Ó¡ÏóÖлáºöÂÔÕâÒ»µã£¬Ê¹ÓÃÄÇЩ²»¿É±äµÄ»ù±¾ÀàÐÍ£¨ÊýÖµ¡¢×Ö·û´®¡¢Ôª×飩ʱҲ¿ÉÒԺܷÅÐĵĺöÊÓËü¡£È»¶ø£¬ÔÚ Python ´úÂëµ÷ÓÃ×ֵ䡢Á´±íÖ®Àà¿É±ä¶ÔÏó£¬ÒÔ¼°´ó¶àÊýÉæ¼°³ÌÐòÍⲿʵÌ壨Îļþ¡¢´°ÌåµÈµÈ£©µÄÀàÐÍʱ£¬ÕâÒ»ÓïÒå¾Í»áÓÐÓ°Ïì¡£ÕâͨÓÃÓÐÖúÓÚÓÅ»¯³ÌÐò£¬ÒòΪ±ðÃûµÄÐÐΪÔÚijЩ·½ÃæÀàËÆÓÚÖ¸Õë¡£ÀýÈ磬ºÜÈÝÒ×´«µÝÒ»¸ö¶ÔÏó£¬ÒòΪÔÚÐÐΪÉÏÖ»ÊÇ´«µÝÁËÒ»¸öÖ¸Õë¡£Èç¹ûº¯ÊýÐÞ¸ÄÁËÒ»¸öͨ¹ý²ÎÊý´«µÝµÄ¶ÔÏ󣬵÷ÓÃÕß¿ÉÒÔ½ÓÊÕµ½±ä»¯££ÔÚ Pascal ÖÐÕâÐèÒªÁ½¸ö²»Í¬µÄ²ÎÊý´«µÝ»úÖÆ¡£
3711
3712 \section{Python Scopes and Name Spaces ×÷ÓÃÓòºÍÃüÃû¿Õ¼ä \label{scopes}}
3713
3714 Before introducing classes, I first have to tell you something about
3715 Python's scope rules. Class definitions play some neat tricks with
3716 namespaces, and you need to know how scopes and namespaces work to
3717 fully understand what's going on. Incidentally, knowledge about this
3718 subject is useful for any advanced Python programmer.
3719
3720 ÔÚ½éÉÜÀà֮ǰ£¬ÎÒÊ×ÏȽéÉÜһЩÓÐ¹Ø Python ×÷ÓÃÓòµÄ¹æÔò£ºÀàµÄ¶¨Òå·Ç³£ÇÉÃîµÄÔËÓÃÁËÃüÃû¿Õ¼ä£¬ÒªÍêÈ«Àí½â½ÓÏÂÀ´µÄ֪ʶ£¬ÐèÒªÏÈÀí½â×÷ÓÃÓòºÍÃüÃû¿Õ¼äµÄ¹¤×÷ÔÀí¡£ÁíÍ⣬ÕâÒ»ÇеÄ֪ʶ¶ÔÓÚÈκθ߼¶ Python ³ÌÐòÔ±¶¼·Ç³£ÓÐÓá£
3721
3722 Let's begin with some definitions.
3723
3724 ÎÒÃÇ´ÓһЩ¶¨Ò忪ʼ¡£
3725
3726 A \emph{namespace} is a mapping from names to objects. Most
3727 namespaces are currently implemented as Python dictionaries, but
3728 that's normally not noticeable in any way (except for performance),
3729 and it may change in the future. Examples of namespaces are: the set
3730 of built-in names (functions such as \function{abs()}, and built-in
3731 exception names); the global names in a module; and the local names in
3732 a function invocation. In a sense the set of attributes of an object
3733 also form a namespace. The important thing to know about namespaces
3734 is that there is absolutely no relation between names in different
3735 namespaces; for instance, two different modules may both define a
3736 function ``maximize'' without confusion --- users of the modules must
3737 prefix it with the module name.
3738
3739 \emph{ÃüÃû¿Õ¼ä}ÊÇ´ÓÃüÃûµ½¶ÔÏóµÄÓ³Éä¡£µ±Ç°\emph{ÃüÃû¿Õ¼ä}Ö÷ÒªÊÇͨ¹ý Python ×ÖµäʵÏֵ쬲»¹ýͨ³£²»¹ØÐľßÌåµÄʵÏÖ·½Ê½£¨³ý·Ç³öÓÚÐÔÄÜ¿¼ÂÇ£©£¬ÒÔºóÒ²ÓпÉÄÜ»á¸Ä±äÆäʵÏÖ·½Ê½¡£ÒÔÏÂÓÐһЩÃüÃû¿Õ¼äµÄÀý×Ó£ºÄÚÖÃÃüÃû£¨Ïñ \function{abs()} ÕâÑùµÄº¯Êý£¬ÒÔ¼°ÄÚÖÃÒì³£Ãû£©¼¯£¬Ä£¿éÖеÄÈ«¾ÖÃüÃû£¬º¯Êýµ÷ÓÃÖеľֲ¿ÃüÃû¡£Ä³ÖÖÒâÒåÉϽ²¶ÔÏóµÄÊôÐÔ¼¯Ò²ÊÇÒ»¸ö\emph{ÃüÃû¿Õ¼ä}¡£¹ØÓÚ\emph{ÃüÃû¿Õ¼ä}ÐèÒªÁ˽âµÄÒ»¼þºÜÖØÒªµÄʾÍÊDz»Í¬\emph{ÃüÃû¿Õ¼ä}ÖеÄÃüÃûûÓÐÈκÎÁªÏµ£¬ÀýÈçÁ½¸ö²»Í¬µÄÄ£¿é¿ÉÄܶ¼»á¶¨ÒåÒ»¸öÃûΪ¡°maximize¡±µÄº¯Êý¶ø²»»á·¢Éú»ìÏý££Óû§±ØÐëÒÔÄ£¿éÃûΪǰ׺À´ÒýÓÃËüÃÇ¡£
3740
3741 By the way, I use the word \emph{attribute} for any name following a
3742 dot --- for example, in the expression \code{z.real}, \code{real} is
3743 an attribute of the object \code{z}. Strictly speaking, references to
3744 names in modules are attribute references: in the expression
3745 \code{modname.funcname}, \code{modname} is a module object and
3746 \code{funcname} is an attribute of it. In this case there happens to
3747 be a straightforward mapping between the module's attributes and the
3748 global names defined in the module: they share the same namespace!
3749 \footnote{
3750 Except for one thing. Module objects have a secret read-only
3751 attribute called \member{__dict__} which returns the dictionary
3752 used to implement the module's namespace; the name
3753 \member{__dict__} is an attribute but not a global name.
3754 Obviously, using this violates the abstraction of namespace
3755 implementation, and should be restricted to things like
3756 post-mortem debuggers.
3757 }
3758
3759 ˳±ãÌáÒ»¾ä£¬ÎÒ³Æ Python ÖÐÈκÎÒ»¸ö¡°.¡±Ö®ºóµÄÃüÃûΪ\emph{ÊôÐÔ}££ÀýÈ磬±í´ïʽ \code{z.real} ÖÐµÄ \code{real} ÊǶÔÏó \code{z} µÄÒ»¸öÊôÐÔ¡£ÑϸñÀ´½²£¬´ÓÄ£¿éÖÐÒýÓÃÃüÃûÊÇÒýÓÃÊôÐÔ£º±í´ïʽ \code{modname.funcname} ÖУ¬ \code{modname} ÊÇÒ»¸öÄ£¿é¶ÔÏó£¬\code{funcname} ÊÇËüµÄÒ»¸öÊôÐÔ¡£Òò´Ë£¬Ä£¿éµÄÊôÐÔºÍÄ£¿éÖеÄÈ«¾ÖÃüÃûÓÐÖ±½ÓµÄÓ³Éä¹ØÏµ£ºËüÃǹ²ÏíͬһÃüÃû¿Õ¼ä£¡\footnote{ ÓÐÒ»¸öÀýÍ⡣ģ¿é¶ÔÏóÓÐÒ»¸öÒþÃØµÄÖ»¶Á¶ÔÏó£¬ÃûΪ __dict__£¬Ëü·µ»ØÓÃÓÚʵÏÖÄ£¿éÃüÃû¿Õ¼äµÄ×ֵ䣬ÃüÃû __dict__ ÊÇÒ»¸öÊôÐÔ¶ø·ÇÈ«¾ÖÃüÃû¡£ÏÔÈ»£¬Ê¹ÓÃËüÎ¥·´ÁËÃüÃû¿Õ¼äʵÏֵijéÏóÔÔò£¬Ó¦¸Ã±»ÑϸñÏÞÖÆÓÚµ÷ÊÔÖС£}
3760
3761 Attributes may be read-only or writable. In the latter case,
3762 assignment to attributes is possible. Module attributes are writable:
3763 you can write \samp{modname.the_answer = 42}. Writable attributes may
3764 also be deleted with the \keyword{del} statement. For example,
3765 \samp{del modname.the_answer} will remove the attribute
3766 \member{the_answer} from the object named by \code{modname}.
3767
3768 ÊôÐÔ¿ÉÒÔÊÇÖ»¶Á¹ý»òдµÄ¡£ºóÒ»ÖÖÇé¿öÏ£¬¿ÉÒÔ¶ÔÊôÐÔ¸³Öµ¡£Äã¿ÉÒÔÕâÑù×÷£º\samp{modname.the_answer = 42}¡£¿ÉдµÄÊôÐÔÒ²¿ÉÒÔÓà \keyword{del} Óï¾äɾ³ý¡£ÀýÈ磺\samp{del modname.the_answer} »á´Ó \code{modname} ¶ÔÏóÖÐɾ³ý \member{the_answer} ÊôÐÔ¡£
3769
3770 Name spaces are created at different moments and have different
3771 lifetimes. The namespace containing the built-in names is created
3772 when the Python interpreter starts up, and is never deleted. The
3773 global namespace for a module is created when the module definition
3774 is read in; normally, module namespaces also last until the
3775 interpreter quits. The statements executed by the top-level
3776 invocation of the interpreter, either read from a script file or
3777 interactively, are considered part of a module called
3778 \module{__main__}, so they have their own global namespace. (The
3779 built-in names actually also live in a module; this is called
3780 \module{__builtin__}.)
3781
3782 ²»Í¬µÄÃüÃû¿Õ¼äÔÚ²»Í¬µÄʱ¿Ì´´½¨£¬Óв»Í¬µÄÉú´æÆÚ¡£°üº¬ÄÚÖÃÃüÃûµÄÃüÃû¿Õ¼äÔÚ Python ½âÊÍÆ÷Æô¶¯Ê±´´½¨£¬»áÒ»Ö±±£Áô£¬²»±»É¾³ý¡£Ä£¿éµÄÈ«¾ÖÃüÃû¿Õ¼äÔÚÄ£¿é¶¨Òå±»¶ÁÈëʱ´´½¨£¬Í¨³££¬Ä£¿éÃüÃû¿Õ¼äÒ²»áÒ»Ö±±£´æµ½½âÊÍÆ÷Í˳ö¡£ÓɽâÊÍÆ÷ÔÚ×î¸ß²ãµ÷ÓÃÖ´ÐеÄÓï¾ä£¬²»¹ÜËüÊǴӽű¾ÎļþÖжÁÈ뻹ÊÇÀ´×Ô½»»¥Ê½ÊäÈ룬¶¼ÊÇ __main__ Ä£¿éµÄÒ»²¿·Ö£¬ËùÒÔËüÃÇÒ²ÓµÓÐ×Ô¼ºµÄÃüÃû¿Õ¼ä¡££¨ÄÚÖÃÃüÃûҲͬÑù±»°üº¬ÔÚÒ»¸öÄ£¿éÖУ¬Ëü±»³Æ×÷ __builtin__ ¡££©
3783
3784 The local namespace for a function is created when the function is
3785 called, and deleted when the function returns or raises an exception
3786 that is not handled within the function. (Actually, forgetting would
3787 be a better way to describe what actually happens.) Of course,
3788 recursive invocations each have their own local namespace.
3789
3790 µ±º¯Êý±»µ÷ÓÃʱ´´½¨Ò»¸ö¾Ö²¿ÃüÃû¿Õ¼ä£¬º¯Êý·´Õý·µ»Ø¹ýÅ׳öÒ»¸öδÔÚº¯ÊýÄÚ´¦ÀíµÄÒ쳣ʱɾ³ý¡££¨Êµ¼ÊÉÏ£¬ËµÊÇÒÅÍü¸üΪÌùÇУ©¡£µ±È»£¬Ã¿Ò»¸öµÝ¹éµ÷ÓÃÓµÓÐ×Ô¼ºµÄÃüÃû¿Õ¼ä¡£
3791
3792 A \emph{scope} is a textual region of a Python program where a
3793 namespace is directly accessible. ``Directly accessible'' here means
3794 that an unqualified reference to a name attempts to find the name in
3795 the namespace.
3796
3797 \emph{×÷ÓÃÓò} ÊÇPython³ÌÐòÖÐÒ»¸öÃüÃû¿Õ¼ä¿ÉÒÔÖ±½Ó·ÃÎʵÄÕýÎÄÇøÓò¡£¡°Ö±½Ó·ÃÎÊ¡±ÔÚÕâÀïµÄÒâ˼ÊDzéÕÒÃüÃûʱÎÞÐèÒýÓÃÃüÃûǰ׺¡£
3798
3799 Although scopes are determined statically, they are used dynamically.
3800 At any time during execution, there are at least three nested scopes whose
3801 namespaces are directly accessible: the innermost scope, which is searched
3802 first, contains the local names; the namespaces of any enclosing
3803 functions, which are searched starting with the nearest enclosing scope;
3804 the middle scope, searched next, contains the current module's global names;
3805 and the outermost scope (searched last) is the namespace containing built-in
3806 names.
3807
3808 ¾¡¹Ü×÷ÓÃÓòÊǾ²Ì¬¶¨Ò壬ÔÚʹÓÃʱËûÃǶ¼ÊǶ¯Ì¬µÄ¡£Ã¿´ÎÖ´ÐÐʱ£¬ÖÁÉÙÓÐÈý¸öÃüÃû¿Õ¼ä¿ÉÒÔÖ±½Ó·ÃÎʵÄ×÷ÓÃÓòǶÌ×ÔÚÒ»Æð£º°üº¬¾Ö²¿ÃüÃûµÄʹÓÃÓòÔÚ×îÀïÃæ£¬Ê×Ïȱ»ËÑË÷£»Æä´ÎËÑË÷µÄÊÇÖвãµÄ×÷ÓÃÓò£¬ÕâÀï°üº¬ÁËͬ¼¶µÄº¯Êý£»×îºóËÑË÷×îÍâÃæµÄ×÷ÓÃÓò£¬Ëü°üº¬ÄÚÖÃÃüÃû¡£
3809
3810 If a name is declared global, then all references and assignments go
3811 directly to the middle scope containing the module's global names.
3812 Otherwise, all variables found outside of the innermost scope are read-only
3813 (an attempt to write to such a variable will simply create a \emph{new}
3814 local variable in the innermost scope, leaving the identically named
3815 outer variable unchanged).
3816
3817 Èç¹ûÒ»¸öÃüÃûÉùÃ÷Ϊȫ¾ÖµÄ£¬ÄÇôËùÓеĸ³ÖµºÍÒýÓö¼Ö±½ÓÕë¶Ô°üº¬Ä£È«¾ÖÃüÃûµÄÖм¶×÷ÓÃÓò¡£ÁíÍ⣬´ÓÍⲿ·ÃÎʵ½µÄËùÓÐÄÚ²ã×÷ÓÃÓòµÄ±äÁ¿¶¼ÊÇÖ»¶ÁµÄ¡££¨ÊÔͼдÕâÑùµÄ±äÁ¿Ö»»áÔÚÄÚ²¿×÷ÓÃÓò´´½¨Ò»¸ö\emph{ÐÂ}¾Ö²¿±äÁ¿£¬Íⲿ±êʾÃüÃûµÄÄǸö±äÁ¿²»»á¸Ä±ä£©¡£
3818
3819 Usually, the local scope references the local names of the (textually)
3820 current function. Outside functions, the local scope references
3821 the same namespace as the global scope: the module's namespace.
3822 Class definitions place yet another namespace in the local scope.
3823
3824 ´Ó×ÖÃæÒâÒåÉϽ²£¬¾Ö²¿×÷ÓÃÓòÒýÓõ±Ç°º¯ÊýµÄÃüÃû¡£ÔÚº¯ÊýÖ®Í⣬¾Ö²¿×÷ÓÃÓòÓëÈ«¾ÖʹÓÃÓòÒýÓÃͬһÃüÃû¿Õ¼ä£ºÄ£¿éÃüÃû¿Õ¼ä¡£ÀඨÒåÒ²ÊǾֲ¿×÷ÓÃÓòÖеÄÁíÒ»¸öÃüÃû¿Õ¼ä¡£
3825
3826 It is important to realize that scopes are determined textually: the
3827 global scope of a function defined in a module is that module's
3828 namespace, no matter from where or by what alias the function is
3829 called. On the other hand, the actual search for names is done
3830 dynamically, at run time --- however, the language definition is
3831 evolving towards static name resolution, at ``compile'' time, so don't
3832 rely on dynamic name resolution! (In fact, local variables are
3833 already determined statically.)
3834
3835 ÖØÒªµÄÊÇ×÷ÓÃÓò¾ö¶¨ÓÚÔ´³ÌÐòµÄÎı¾£ºÒ»¸ö¶¨ÒåÓÚijģ¿éÖеĺ¯ÊýµÄÈ«¾Ö×÷ÓÃÓòÊǸÃÄ£¿éµÄÃüÃû¿Õ¼ä£¬¶ø²»ÊǸú¯ÊýµÄ±ðÃû±»¶¨Òå»òµ÷ÓõÄλÖã¬Á˽âÕâÒ»µã·Ç³£ÖØÒª¡£ÁíÒ»·½Ã棬ÃüÃûµÄʵ¼ÊËÑË÷¹ý³ÌÊǶ¯Ì¬µÄ£¬ÔÚÔËÐÐʱȷ¶¨µÄ¡ª¡ªÈ»¶ø£¬Python ÓïÑÔÒ²ÔÚ²»¶Ï·¢Õ¹£¬ÒÔºóÓпÉÄÜ»á³ÉΪ¾²Ì¬µÄ¡°±àÒ롱ʱȷ¶¨£¬ËùÒÔ²»ÒªÒÀÀµ¶¯Ì¬½âÎö£¡£¨ÊÂʵÉÏ£¬¾Ö²¿±äÁ¿ÒѾÊǾ²Ì¬È·¶¨ÁË¡££©
3836
3837 A special quirk of Python is that assignments always go into the
3838 innermost scope. Assignments do not copy data --- they just
3839 bind names to objects. The same is true for deletions: the statement
3840 \samp{del x} removes the binding of \code{x} from the namespace
3841 referenced by the local scope. In fact, all operations that introduce
3842 new names use the local scope: in particular, import statements and
3843 function definitions bind the module or function name in the local
3844 scope. (The \keyword{global} statement can be used to indicate that
3845 particular variables live in the global scope.)
3846
3847 Python µÄÒ»¸öÌØ±ðÖ®´¦ÔÚÓÚÆä¸³Öµ²Ù×÷×ÜÊÇÔÚ×îÀï²ãµÄ×÷ÓÃÓò¡£¸³Öµ²»»á¸´ÖÆÊý¾Ý¡ª¡ªÖ»Êǽ«ÃüÃû°ó¶¨µ½¶ÔÏó¡£É¾³ýÒ²ÊÇÈç´Ë£º\samp{del x} Ö»ÊÇ´Ó¾Ö²¿×÷ÓÃÓòµÄÃüÃû¿Õ¼äÖÐɾ³ýÃüÃû \code{x} ¡£ÊÂʵÉÏ£¬ËùÓÐÒýÈëÐÂÃüÃûµÄ²Ù×÷¶¼×÷ÓÃÓÚ¾Ö²¿×÷ÓÃÓò¡£ÌرðÊÇ import Óï¾äºÍº¯Êý¶¨½«Ä£¿éÃû»òº¯Êý°ó¶¨ÓÚ¾Ö²¿×÷ÓÃÓò¡££¨¿ÉÒÔʹÓà global Óï¾ä½«±äÁ¿ÒýÈ뵽ȫ¾Ö×÷ÓÃÓò¡££©
3848
3849 \section{A First Look at Classes ³õʶÀà \label{firstClasses}}
3850
3851 Classes introduce a little bit of new syntax, three new object types,
3852 and some new semantics.
3853
3854 ÀàÒýÈëÁËÒ»µãеÄÓï·¨£¬ÈýÖÖеĶÔÏóÀàÐÍ£¬ÒÔ¼°Ò»Ð©ÐµÄÓïÒå¡£
3855
3856 \subsection{Class Definition Syntax ÀඨÒåÓï·¨ \label{classDefinition}}
3857
3858 The simplest form of class definition looks like this:
3859
3860 ×î¼òµ¥µÄÀඨÒåÐÎʽÈçÏ£º
3861
3862 \begin{verbatim}
3863 class ClassName:
3864 <statement-1>
3865 .
3866 .
3867 .
3868 <statement-N>
3869 \end{verbatim}
3870
3871 Class definitions, like function definitions
3872 (\keyword{def} statements) must be executed before they have any
3873 effect. (You could conceivably place a class definition in a branch
3874 of an \keyword{if} statement, or inside a function.)
3875
3876 ÀàµÄ¶¨Òå¾ÍÏñº¯Êý¶¨Ò壨 \keyword{def} Óï¾ä£©£¬ÒªÏÈÖ´ÐвÅÄÜÉúЧ¡££¨Ä㵱Ȼ¿ÉÒÔ°ÑËü·Å½ø \keyword{if} Óï¾äµÄijһ·ÖÖ§£¬»òÕßÒ»¸öº¯ÊýµÄÄÚ²¿¡££©
3877
3878 In practice, the statements inside a class definition will usually be
3879 function definitions, but other statements are allowed, and sometimes
3880 useful --- we'll come back to this later. The function definitions
3881 inside a class normally have a peculiar form of argument list,
3882 dictated by the calling conventions for methods --- again, this is
3883 explained later.
3884
3885 ϰ¹ßÉÏ£¬ÀඨÒåÓï¾äµÄÄÚÈÝͨ³£ÊǺ¯Êý¶¨Ò壬²»¹ýÆäËüÓï¾äÒ²¿ÉÒÔ£¬ÓÐʱ»áºÜÓÐÓ᪡ªºóÃæÎÒÃÇÔٻعýÍ·À´ÌÖÂÛ¡£ÀàÖеĺ¯Êý¶¨Òåͨ³£°üÀ¨ÁËÒ»¸öÌØÊâÐÎʽµÄ²ÎÊýÁÐ±í£¬ÓÃÓÚ·½·¨µ÷ÓÃÔ¼¶¨¡ª¡ªÍ¬ÑùÎÒÃÇÔÚºóÃæÌÖÂÛÕâЩ¡£
3886
3887 When a class definition is entered, a new namespace is created, and
3888 used as the local scope --- thus, all assignments to local variables
3889 go into this new namespace. In particular, function definitions bind
3890 the name of the new function here.
3891
3892 ϰ¹ßÉÏ£¬ÀඨÒåÓï¾äµÄÄÚÈÝͨ³£ÊǺ¯Êý¶¨Ò壬²»¹ýÆäËüÓï¾äÒ²¿ÉÒÔ£¬ÓÐʱ»áºÜÓÐÓ᪡ªºóÃæÎÒÃÇÔٻعýÍ·À´ÌÖÂÛ¡£ÀàÖеĺ¯Êý¶¨Òåͨ³£°üÀ¨ÁËÒ»¸öÌØÊâÐÎʽµÄ²ÎÊýÁÐ±í£¬ÓÃÓÚ·½·¨µ÷ÓÃÔ¼¶¨¡ª¡ªÍ¬ÑùÎÒÃÇÔÚºóÃæÌÖÂÛÕâЩ¡£
3893
3894 When a class definition is left normally (via the end), a \emph{class
3895 object} is created. This is basically a wrapper around the contents
3896 of the namespace created by the class definition; we'll learn more
3897 about class objects in the next section. The original local scope
3898 (the one in effect just before the class definition was entered) is
3899 reinstated, and the class object is bound here to the class name given
3900 in the class definition header (\class{ClassName} in the example).
3901
3902 ÀඨÒåÍê³Éʱ£¨Õý³£Í˳ö£©£¬¾Í´´½¨ÁËÒ»¸ö\emph{Àà¶ÔÏó}¡£»ù±¾ÉÏËüÊǶÔÀඨÒå´´½¨µÄÃüÃû¿Õ¼ä½øÐÐÁËÒ»¸ö°ü×°£»ÎÒÃÇÔÚÏÂÒ»½Ú½øÒ»²½Ñ§Ï°Àà¶ÔÏóµÄ֪ʶ¡£ÔʼµÄ¾Ö²¿×÷ÓÃÓò£¨ÀඨÒåÒýÈë֮ǰÉúЧµÄÄǸö£©µÃµ½»Ö¸´£¬Àà¶ÔÏóÔÚÕâÀï°ó¶¨µ½ÀඨÒåÍ·²¿µÄÀàÃû£¨Àý×ÓÖÐÊÇ \class{ClassName} £©¡£
3903
3904 \subsection{Class Objects Àà¶ÔÏó \label{classObjects}}
3905
3906 Class objects support two kinds of operations: attribute references
3907 and instantiation.
3908
3909 Àà¶ÔÏóÖ§³ÖÁ½ÖÖ²Ù×÷£ºÊôÐÔÒýÓúÍʵÀý»¯¡£
3910
3911 \emph{Attribute references} use the standard syntax used for all
3912 attribute references in Python: \code{obj.name}. Valid attribute
3913 names are all the names that were in the class's namespace when the
3914 class object was created. So, if the class definition looked like
3915 this:
3916
3917 ÊôÐÔÒýÓÃʹÓÃºÍ Python ÖÐËùÓеÄÊôÐÔÒýÓÃÒ»ÑùµÄ±ê×¼Óï·¨£º\code{obj.name}¡£Àà¶ÔÏó´´½¨ºó£¬ÀàÃüÃû¿Õ¼äÖÐËùÓеÄÃüÃû¶¼ÊÇÓÐЧÊôÐÔÃû¡£ËùÒÔÈç¹ûÀඨÒåÊÇÕâÑù£º
3918
3919 \begin{verbatim}
3920 class MyClass:
3921 "A simple example class"
3922 i = 12345
3923 def f(self):
3924 return 'hello world'
3925 \end{verbatim}
3926
3927 then \code{MyClass.i} and \code{MyClass.f} are valid attribute
3928 references, returning an integer and a function object, respectively.
3929 Class attributes can also be assigned to, so you can change the value
3930 of \code{MyClass.i} by assignment. \member{__doc__} is also a valid
3931 attribute, returning the docstring belonging to the class: \code{"A
3932 simple example class"}.
3933
3934 ÄÇô \code{MyClass.i} ºÍ \code{MyClass.f} ÊÇÓÐЧµÄÊôÐÔÒýÓ㬷ֱ𷵻ØÒ»¸öÕûÊýºÍÒ»¸ö·½·¨¶ÔÏó¡£Ò²¿ÉÒÔ¶ÔÀàÊôÐÔ¸³Öµ£¬Äã¿ÉÒÔͨ¹ý¸ø\code{MyClass.i} ¸³ÖµÀ´ÐÞ¸ÄËü¡£ \member{__doc__} Ò²ÊÇÒ»¸öÓÐЧµÄÊôÐÔ£¬·µ»ØÀàµÄÎĵµ×Ö·û´®£º \code{"A simple example class"}¡£
3935
3936 Class \emph{instantiation} uses function notation. Just pretend that
3937 the class object is a parameterless function that returns a new
3938 instance of the class. For example (assuming the above class):
3939
3940 ÀàµÄʵÀý»¯Ê¹Óú¯Êý·ûºÅ¡£Ö»Òª½«Àà¶ÔÏó¿´×÷ÊÇÒ»¸ö·µ»ØÐµÄÀàʵÀýµÄÎÞ²ÎÊýº¯Êý¼´¿É¡£ÀýÈ磨¼ÙÉèÑØÓÃÇ°ÃæµÄÀࣩ£º
3941
3942 \begin{verbatim}
3943 x = MyClass()
3944 \end{verbatim}
3945
3946 creates a new \emph{instance} of the class and assigns this object to
3947 the local variable \code{x}.
3948
3949 ÒÔÉÏ´´½¨ÁËÒ»¸öеÄÀà\emph{ʵÀý}²¢½«¸Ã¶ÔÏ󸳸ø¾Ö²¿±äÁ¿ \code{x}¡£
3950
3951 The instantiation operation (``calling'' a class object) creates an
3952 empty object. Many classes like to create objects with instances
3953 customized to a specific initial state.
3954 Therefore a class may define a special method named
3955 \method{__init__()}, like this:
3956
3957 Õâ¸öʵÀý»¯²Ù×÷£¨¡°µ÷Óá±Ò»¸öÀà¶ÔÏó£©À´´´½¨Ò»¸ö¿ÕµÄ¶ÔÏ󡣺ܶàÀà¶¼ÇãÏòÓÚ½«¶ÔÏó´´½¨ÎªÓгõʼ״̬µÄ¡£Òò´ËÀà¿ÉÄܻᶨÒåÒ»¸öÃûΪ \method{__init__()} µÄÌØÊâ·½·¨£¬ÏñÏÂÃæÕâÑù£º
3958
3959 \begin{verbatim}
3960 def __init__(self):
3961 self.data = []
3962 \end{verbatim}
3963
3964 When a class defines an \method{__init__()} method, class
3965 instantiation automatically invokes \method{__init__()} for the
3966 newly-created class instance. So in this example, a new, initialized
3967 instance can be obtained by:
3968
3969 ÀඨÒåÁË \method{__init__()} ·½·¨µÄ»°£¬ÀàµÄʵÀý»¯²Ù×÷»á×Ô¶¯ÎªÐ´´½¨µÄÀàʵÀýµ÷Óà \method{__init__()} ·½·¨¡£ËùÒÔÔÚÏÂÀýÖУ¬¿ÉÒÔÕâÑù´´½¨Ò»¸öеÄʵÀý£º
3970
3971 \begin{verbatim}
3972 x = MyClass()
3973 \end{verbatim}
3974
3975 Of course, the \method{__init__()} method may have arguments for
3976 greater flexibility. In that case, arguments given to the class
3977 instantiation operator are passed on to \method{__init__()}. For
3978 example,
3979
3980 µ±È»£¬³öÓÚµ¯ÐÔµÄÐèÒª£¬ \method{__init__()} ·½·¨¿ÉÒÔÓвÎÊý¡£ÊÂʵÉÏ£¬²ÎÊýͨ¹ý \method{__init__()} ´«µÝµ½ÀàµÄʵÀý»¯²Ù×÷ÉÏ¡£ÀýÈ磺
3981
3982 \begin{verbatim}
3983 >>> class Complex:
3984 ... def __init__(self, realpart, imagpart):
3985 ... self.r = realpart
3986 ... self.i = imagpart
3987 ...
3988 >>> x = Complex(3.0, -4.5)
3989 >>> x.r, x.i
3990 (3.0, -4.5)
3991 \end{verbatim}
3992
3993
3994 \subsection{Instance Objects ʵÀý¶ÔÏó \label{instanceObjects}}
3995
3996 Now what can we do with instance objects? The only operations
3997 understood by instance objects are attribute references. There are
3998 two kinds of valid attribute names, data attributes and methods.
3999
4000 ÏÖÔÚÎÒÃÇ¿ÉÒÔÓÃʵÀý¶ÔÏó×÷ʲô£¿ÊµÀý¶ÔÏóΨһ¿ÉÓõIJÙ×÷¾ÍÊÇÊôÐÔÒýÓá£ÓÐÁ½ÖÖÓÐЧµÄÊôÐÔÃû¡£
4001
4002 \emph{data attributes} correspond to
4003 ``instance variables'' in Smalltalk, and to ``data members'' in
4004 \Cpp. Data attributes need not be declared; like local variables,
4005 they spring into existence when they are first assigned to. For
4006 example, if \code{x} is the instance of \class{MyClass} created above,
4007 the following piece of code will print the value \code{16}, without
4008 leaving a trace:
4009
4010 Êý¾ÝÊôÐÔÏ൱ÓÚ Smalltalk Öеġ°ÊµÀý±äÁ¿¡±»ò \Cpp Öеġ°Êý¾Ý³ÉÔ±¡±¡£ºÍ¾Ö²¿±äÁ¿Ò»Ñù£¬Êý¾ÝÊôÐÔ²»ÐèÒªÉùÃ÷£¬µÚÒ»´ÎʹÓÃʱËüÃǾͻáÉú³É¡£ÀýÈ磬Èç¹û \code{x} ÊÇÇ°Ãæ´´½¨µÄ \class{MyClass} ʵÀý£¬ÏÂÃæÕâ¶Î´úÂë»á´òÓ¡³ö \code{16} ¶ø²»»áÓÐÈκζàÓàµÄ²ÐÁô£º
4011
4012 \begin{verbatim}
4013 x.counter = 1
4014 while x.counter < 10:
4015 x.counter = x.counter * 2
4016 print x.counter
4017 del x.counter
4018 \end{verbatim}
4019
4020 The other kind of instance attribute reference is a \emph{method}.
4021 A method is a function that ``belongs to'' an
4022 object. (In Python, the term method is not unique to class instances:
4023 other object types can have methods as well. For example, list objects have
4024 methods called append, insert, remove, sort, and so on. However,
4025 in the following discussion, we'll use the term method exclusively to mean
4026 methods of class instance objects, unless explicitly stated otherwise.)
4027
4028 ÁíÒ»ÖÖΪʵÀý¶ÔÏóËù½ÓÊܵÄÒýÓÃÊôÐÔÊÇ·½·¨¡£·½·¨ÊÇ¡°ÊôÓÚ¡±Ò»¸ö¶ÔÏóµÄº¯Êý¡££¨ÔÚ Python ÖУ¬·½·¨²»Ö¹ÊÇÀàʵÀýËù¶ÀÓУºÆäËüÀàÐ͵ĶÔÏóÒ²¿ÉÓÐ\emph{·½·¨}¡£ÀýÈ磬Á´±í¶ÔÏóÓÐ append£¬insert£¬remove£¬sort µÈµÈ·½·¨¡£È»¶ø£¬ÔÚºóÃæµÄ½éÉÜÖУ¬³ý·ÇÌØ±ð˵Ã÷£¬ÎÒÃÇÌáµ½µÄ·½·¨ÌØÖ¸Àà·½·¨£©
4029
4030 Valid method names of an instance object depend on its class. By
4031 definition, all attributes of a class that are function
4032 objects define corresponding methods of its instances. So in our
4033 example, \code{x.f} is a valid method reference, since
4034 \code{MyClass.f} is a function, but \code{x.i} is not, since
4035 \code{MyClass.i} is not. But \code{x.f} is not the same thing as
4036 \code{MyClass.f} --- it is a \obindex{method}\emph{method object}, not
4037 a function object.
4038
4039 ʵÀý¶ÔÏóµÄÓÐЧÃû³ÆÒÀÀµÓÚËüµÄÀà¡£°´ÕÕ¶¨Ò壬ÀàÖÐËùÓУ¨Óû§¶¨Ò壩µÄº¯Êý¶ÔÏó¶ÔÓ¦ËüµÄʵÀýÖеķ½·¨¡£ËùÒÔÔÚÎÒÃǵÄÀý×ÓÖУ¬\code{x.f} ÊÇÒ»¸öÓÐЧµÄ·½·¨ÒýÓã¬ÒòΪ \code{MyClass.f} ÊÇÒ»¸öº¯Êý¡£µ« \code{x.i} ²»ÊÇ£¬ÒòΪ \code{MyClass.i} ÊDz»ÊǺ¯Êý¡£²»¹ý \code{x.f} ºÍ \code{MyClass.f} ²»Í¬££ËüÊÇÒ»¸ö·½·¨¶ÔÏ󣬲»ÊÇÒ»¸öº¯Êý¶ÔÏó¡£
4040
4041 \subsection{Method Objects ·½·¨¶ÔÏó \label{methodObjects}}
4042
4043 Usually, a method is called right after it is bound:
4044
4045 ͨ³££¬·½·¨Í¨¹ýÓҰ󶨵÷Óãº
4046
4047 \begin{verbatim}
4048 x.f()
4049 \end{verbatim}
4050
4051 In the \class{MyClass} example, this will return the string \code{'hello world'}.
4052 However, it is not necessary to call a method right away:
4053 \code{x.f} is a method object, and can be stored away and called at a
4054 later time. For example:
4055
4056 ÔÚ \class{MyClass} ʾÀýÖУ¬Õâ»á·µ»Ø×Ö·û´® \code{'hello world'} ¡£È»¶ø£¬Ò²²»ÊÇÒ»¶¨ÒªÖ±½Óµ÷Ó÷½·¨¡£ \code{x.f} ÊÇÒ»¸ö·½·¨¶ÔÏó£¬Ëü¿ÉÒÔ´æ´¢ÆðÀ´ÒÔºóµ÷Óá£ÀýÈ磺
4057
4058 \begin{verbatim}
4059 xf = x.f
4060 while True:
4061 print xf()
4062 \end{verbatim}
4063
4064 will continue to print \samp{hello world} until the end of time.
4065
4066 »á²»¶ÏµÄ´òÓ¡ \samp{hello world} ¡£
4067
4068 What exactly happens when a method is called? You may have noticed
4069 that \code{x.f()} was called without an argument above, even though
4070 the function definition for \method{f} specified an argument. What
4071 happened to the argument? Surely Python raises an exception when a
4072 function that requires an argument is called without any --- even if
4073 the argument isn't actually used...
4074
4075 µ÷Ó÷½·¨Ê±·¢ÉúÁËʲô£¿Äã¿ÉÄÜ×¢Òâµ½µ÷Óà \code{x.f()} ʱûÓÐÒýÓÃÇ°Ãæ±ê³öµÄ±äÁ¿£¬¾¡¹ÜÔÚ \method{f} µÄº¯Êý¶¨ÒåÖÐÖ¸Ã÷ÁËÒ»¸ö²ÎÊý¡£Õâ¸ö²ÎÊýÔõôÁË£¿ÊÂʵÉÏÈç¹ûº¯Êýµ÷ÓÃÖÐȱÉÙ²ÎÊý£¬Python »áÅ׳öÒì³£££ÉõÖÁÕâ¸ö²ÎÊýʵ¼ÊÉÏûʲôÓá¡
4076
4077 Actually, you may have guessed the answer: the special thing about
4078 methods is that the object is passed as the first argument of the
4079 function. In our example, the call \code{x.f()} is exactly equivalent
4080 to \code{MyClass.f(x)}. In general, calling a method with a list of
4081 \var{n} arguments is equivalent to calling the corresponding function
4082 with an argument list that is created by inserting the method's object
4083 before the first argument.
4084
4085 ʵ¼ÊÉÏ£¬Äã¿ÉÄÜÒѾ²Âµ½Á˴𰸣º·½·¨µÄÌØ±ðÖ®´¦ÔÚÓÚʵÀý¶ÔÏó×÷Ϊº¯ÊýµÄµÚÒ»¸ö²ÎÊý´«¸øÁ˺¯Êý¡£ÔÚÎÒÃǵÄÀý×ÓÖУ¬µ÷Óà \code{x.f()} Ï൱ÓÚ \code{MyClass.f(x)} ¡£Í¨³££¬ÒÔ \var{n} ¸ö²ÎÊýµÄÁбíÈ¥µ÷ÓÃÒ»¸ö·½·¨¾ÍÏ൱ÓÚ½«·½·¨µÄ¶ÔÏó²åÈëµ½²ÎÊýÁбíµÄ×îÇ°Ãæºó£¬ÒÔÕâ¸öÁбíÈ¥µ÷ÓÃÏàÓ¦µÄº¯Êý¡£
4086
4087 If you still don't understand how methods work, a look at the
4088 implementation can perhaps clarify matters. When an instance
4089 attribute is referenced that isn't a data attribute, its class is
4090 searched. If the name denotes a valid class attribute that is a
4091 function object, a method object is created by packing (pointers to)
4092 the instance object and the function object just found together in an
4093 abstract object: this is the method object. When the method object is
4094 called with an argument list, it is unpacked again, a new argument
4095 list is constructed from the instance object and the original argument
4096 list, and the function object is called with this new argument list.
4097
4098 Èç¹ûÄ㻹ÊDz»Àí½â·½·¨µÄ¹¤×÷ÔÀí£¬Á˽âÒ»ÏÂËüµÄʵÏÖÒ²ÐíÓаïÖú¡£ÒýÓ÷ÇÊý¾ÝÊôÐÔµÄʵÀýÊôÐÔʱ£¬»áËÑË÷ËüµÄÀà¡£Èç¹ûÕâ¸öÃüÃûÈ·ÈÏΪһ¸öÓÐЧµÄº¯Êý¶ÔÏóÀàÊôÐÔ£¬¾Í»á½«ÊµÀý¶ÔÏóºÍº¯Êý¶ÔÏó·â×°½øÒ»¸ö³éÏó¶ÔÏó£ºÕâ¾ÍÊÇ·½·¨¶ÔÏó¡£ÒÔÒ»¸ö²ÎÊýÁбíµ÷Ó÷½·¨¶ÔÏóʱ£¬Ëü±»ÖØÐ²ð·â£¬ÓÃʵÀý¶ÔÏóºÍÔʼµÄ²ÎÊýÁÐ±í¹¹ÔìÒ»¸öеIJÎÊýÁÐ±í£¬È»ºóº¯Êý¶ÔÏóµ÷ÓÃÕâ¸öеIJÎÊýÁÐ±í¡£
4099
4100
4101 \section{Random Remarks һЩ˵Ã÷ \label{remarks}}
4102
4103 % [These should perhaps be placed more carefully...]
4104
4105
4106 Data attributes override method attributes with the same name; to
4107 avoid accidental name conflicts, which may cause hard-to-find bugs in
4108 large programs, it is wise to use some kind of convention that
4109 minimizes the chance of conflicts. Possible conventions include
4110 capitalizing method names, prefixing data attribute names with a small
4111 unique string (perhaps just an underscore), or using verbs for methods
4112 and nouns for data attributes.
4113
4114 ͬÃûµÄÊý¾ÝÊôÐԻḲ¸Ç·½·¨ÊôÐÔ£¬ÎªÁ˱ÜÃâ¿ÉÄܵÄÃüÃû³åÍ»££ÕâÔÚ´óÐͳÌÐòÖпÉÄܻᵼÖÂÄÑÒÔ·¢ÏÖµÄ bug ££×îºÃÒÔijÖÖÃüÃûÔ¼¶¨À´±ÜÃâ³åÍ»¡£¿ÉÑ¡µÄÔ¼¶¨°üÀ¨·½·¨µÄÊ××Öĸ´óд£¬Êý¾ÝÊôÐÔÃûǰ׺Сд£¨¿ÉÄÜÖ»ÊÇÒ»¸öÏ»®Ïߣ©£¬»òÕß·½·¨Ê¹Óö¯´Ê¶øÊý¾ÝÊôÐÔʹÓÃÃû´Ê¡£
4115
4116 Data attributes may be referenced by methods as well as by ordinary
4117 users (``clients'') of an object. In other words, classes are not
4118 usable to implement pure abstract data types. In fact, nothing in
4119 Python makes it possible to enforce data hiding --- it is all based
4120 upon convention. (On the other hand, the Python implementation,
4121 written in C, can completely hide implementation details and control
4122 access to an object if necessary; this can be used by extensions to
4123 Python written in C.)
4124
4125 Êý¾ÝÊôÐÔ¿ÉÒÔÓÉ·½·¨ÒýÓã¬Ò²¿ÉÒÔÓÉÆÕͨÓû§£¨¿Í»§£©µ÷Ó᣻»¾ä»°Ëµ£¬À಻ÄÜʵÏÖ´¿µÄÊý¾ÝÀàÐÍ¡£ÊÂʵÉÏ Python ÖÐûÓÐʲô°ì·¨¿ÉÒÔÇ¿ÖÆÒþ²ØÊý¾Ý££Ò»Çж¼»ù±¾Ô¼¶¨µÄ¹ßÀý¡££¨ÁíÒ»·½·¨½²£¬Python µÄʵÏÖÊÇÓà C д³ÉµÄ£¬Èç¹ûÓбØÒª£¬¿ÉÒÔÓà C À´±àд Python À©Õ¹£¬ÍêÈ«Òþ²ØÊµÏÖµÄϸ½Ú£¬¿ØÖƶÔÏóµÄ·ÃÎÊ¡££©
4126
4127 Clients should use data attributes with care --- clients may mess up
4128 invariants maintained by the methods by stamping on their data
4129 attributes. Note that clients may add data attributes of their own to
4130 an instance object without affecting the validity of the methods, as
4131 long as name conflicts are avoided --- again, a naming convention can
4132 save a lot of headaches here.
4133
4134 ¿Í»§Ó¦¸ÃСÐÄʹÓÃÊý¾ÝÊôÐÔ££¿Í»§¿ÉÄÜ»áÒòÎªËæÒâÐÞ¸ÄÊý¾ÝÊôÐÔ¶øÆÆ»µÁ˱¾À´ÓÉ·½·¨Î¬»¤µÄÊý¾ÝÒ»ÖÂÐÔ¡£ÐèҪעÒâµÄÊÇ£¬¿Í»§Ö»Òª×¢Òâ±ÜÃâÃüÃû³åÍ»£¬¾Í¿ÉÒÔËæÒâÏòʵÀýÖÐÌí¼ÓÊý¾ÝÊôÐÔ¶ø²»»áÓ°Ïì·½·¨µÄÓÐЧÐÔ££ÔÙ´ÎÇ¿µ÷£¬ÃüÃûÔ¼¶¨¿ÉÒÔʡȥºÜ¶àÂé·³¡£
4135
4136 There is no shorthand for referencing data attributes (or other
4137 methods!) from within methods. I find that this actually increases
4138 the readability of methods: there is no chance of confusing local
4139 variables and instance variables when glancing through a method.
4140
4141 ´Ó·½·¨ÄÚ²¿ÒýÓÃÊý¾ÝÊôÐÔ£¨ÒÔ¼°ÆäËü·½·¨£¡£©Ã»ÓÐʲô¿ì½ÝµÄ·½Ê½¡£ÎÒÈÏΪÕâÊÂʵÉÏÔö¼ÓÁË·½·¨µÄ¿É¶ÁÐÔ£º¼´Ê¹´ÖÂÔµÄä¯ÀÀÒ»¸ö·½·¨£¬Ò²²»»áÓлìÏý¾Ö²¿±äÁ¿ºÍʵÀý±äÁ¿µÄ»ú»á¡£
4142
4143 Often, the first argument of a method is called
4144 \code{self}. This is nothing more than a convention: the name
4145 \code{self} has absolutely no special meaning to Python. (Note,
4146 however, that by not following the convention your code may be less
4147 readable to other Python programmers, and it is also conceivable that
4148 a \emph{class browser} program might be written that relies upon such a
4149 convention.)
4150
4151 ͨ³£·½·¨µÄµÚÒ»¸ö²ÎÊýÃüÃûΪ \code{self} ¡£Õâ½ö½öÊÇÒ»¸öÔ¼¶¨£º¶Ô Python ¶øÑÔ£¬\code{self} ¾ø¶ÔûÓÐÈκÎÌØÊ⺬Òå¡££¨È»¶øÒª×¢ÒâµÄÊÇ£¬Èç¹û²»×ñÊØÕâ¸öÔ¼¶¨£¬±ðµÄ Python ³ÌÐòÔ±ÔĶÁÄãµÄ´úÂëʱ»áÓв»±ã£¬¶øÇÒÓÐЩÀàä¯ÀÀ³ÌÐòÒ²ÊÇ×ñÑ´ËÔ¼¶¨¿ª·¢µÄ¡££©
4152
4153 Any function object that is a class attribute defines a method for
4154 instances of that class. It is not necessary that the function
4155 definition is textually enclosed in the class definition: assigning a
4156 function object to a local variable in the class is also ok. For
4157 example:
4158
4159 ÀàÊôÐÔÖеÄÈκκ¯Êý¶ÔÏóÔÚÀàʵÀýÖж¼¶¨ÒåΪ·½·¨¡£²»ÊDZØÐëÒª½«º¯Êý¶¨Òå´úÂëд½øÀඨÒåÖУ¬Ò²¿ÉÒÔ½«Ò»¸öº¯Êý¶ÔÏ󸳸øÀàÖеÄÒ»¸ö±äÁ¿¡£ÀýÈ磺
4160
4161 \begin{verbatim}
4162 # Function defined outside the class
4163 def f1(self, x, y):
4164 return min(x, x+y)
4165
4166 class C:
4167 f = f1
4168 def g(self):
4169 return 'hello world'
4170 h = g
4171 \end{verbatim}
4172
4173 Now \code{f}, \code{g} and \code{h} are all attributes of class
4174 \class{C} that refer to function objects, and consequently they are all
4175 methods of instances of \class{C} --- \code{h} being exactly equivalent
4176 to \code{g}. Note that this practice usually only serves to confuse
4177 the reader of a program.
4178
4179 ÏÖÔÚ \code{f}, \code{g} ºÍ \code{h} ¶¼ÊÇÀà \class{C} µÄÊôÐÔ£¬ÒýÓõͼÊǺ¯Êý¶ÔÏó£¬Òò´ËËüÃǶ¼ÊÇ \class{C} ʵÀýµÄ·½·¨££ \code{h} ÑϸñµÈÓÚ \code{g}¡£Òª×¢ÒâµÄÊÇÕâÖÖϰ¹ßͨ³£Ö»»áÃÔ»ó³ÌÐòµÄ¶ÁÕß¡£
4180
4181 Methods may call other methods by using method attributes of the
4182 \code{self} argument:
4183
4184 ͨ¹ý \code{self} ²ÎÊýµÄ·½·¨ÊôÐÔ£¬·½·¨¿ÉÒÔµ÷ÓÃÆäËüµÄ·½·¨£º
4185
4186 \begin{verbatim}
4187 class Bag:
4188 def __init__(self):
4189 self.data = []
4190 def add(self, x):
4191 self.data.append(x)
4192 def addtwice(self, x):
4193 self.add(x)
4194 self.add(x)
4195 \end{verbatim}
4196
4197 Methods may reference global names in the same way as ordinary
4198 functions. The global scope associated with a method is the module
4199 containing the class definition. (The class itself is never used as a
4200 global scope!) While one rarely encounters a good reason for using
4201 global data in a method, there are many legitimate uses of the global
4202 scope: for one thing, functions and modules imported into the global
4203 scope can be used by methods, as well as functions and classes defined
4204 in it. Usually, the class containing the method is itself defined in
4205 this global scope, and in the next section we'll find some good
4206 reasons why a method would want to reference its own class!
4207
4208 ·½·¨¿ÉÒÔÏñÒýÓÃÆÕͨµÄº¯ÊýÄÇÑùÒýÓÃÈ«¾ÖÃüÃû¡£Óë·½·¨¹ØÁªµÄÈ«¾Ö×÷ÓÃÓòÊǰüº¬ÀඨÒåµÄÄ£¿é¡££¨Àà±¾ÉíÓÀÔ¶²»»á×öΪȫ¾Ö×÷ÓÃÓòʹÓã¡£©¾¡¹ÜºÜÉÙÓкõÄÀíÓÉÔÚ·½·¨ÖÐʹÓÃÈ«¾ÖÊý¾Ý£¬È«¾Ö×÷ÓÃÓòÈ·ÓкܶàºÏ·¨µÄÓÃ;£ºÆäÒ»ÊÇ·½·¨¿ÉÒÔµ÷Óõ¼ÈëÈ«¾Ö×÷ÓÃÓòµÄº¯ÊýºÍ·½·¨£¬Ò²¿ÉÒÔµ÷Óö¨ÒåÔÚÆäÖеÄÀàºÍº¯Êý¡£Í¨³££¬°üº¬´Ë·½·¨µÄÀàÒ²»á¶¨ÒåÔÚÕâ¸öÈ«¾Ö×÷ÓÃÓò£¬ÔÚÏÂÒ»½ÚÎÒÃÇ»áÁ˽âΪºÎÒ»¸ö·½·¨ÒªÒýÓÃ×Ô¼ºµÄÀ࣡
4209
4210 \section{Inheritance ¼Ì³Ð \label{inheritance}}
4211
4212 Of course, a language feature would not be worthy of the name ``class''
4213 without supporting inheritance. The syntax for a derived class
4214 definition looks like this:
4215
4216 µ±È»£¬Èç¹ûÒ»ÖÖÓïÑÔ²»Ö§³Ö¼Ì³Ð¾Í£¬¡°Àࡱ¾ÍûÓÐʲôÒâÒå¡£ÅÉÉúÀàµÄ¶¨ÒåÈçÏÂËùʾ£º
4217
4218 \begin{verbatim}
4219 class DerivedClassName(BaseClassName):
4220 <statement-1>
4221 .
4222 .
4223 .
4224 <statement-N>
4225 \end{verbatim}
4226
4227 The name \class{BaseClassName} must be defined in a scope containing
4228 the derived class definition. In place of a base class name, other
4229 arbitrary expressions are also allowed. This can be useful, for
4230 example, when the base class is defined in another module:
4231
4232 ÃüÃû \class{BaseClassName}£¨Ê¾ÀýÖеĻùÀàÃû£©±ØÐëÓëÅÉÉúÀඨÒåÔÚÒ»¸ö×÷ÓÃÓòÄÚ¡£³ýÁËÀ࣬»¹¿ÉÒÔÓñí´ïʽ£¬»ùÀඨÒåÔÚÁíÒ»¸öÄ£¿éÖÐʱÕâÒ»µã·Ç³£ÓÐÓãº
4233
4234 \begin{verbatim}
4235 class DerivedClassName(modname.BaseClassName):
4236 \end{verbatim}
4237
4238 Execution of a derived class definition proceeds the same as for a
4239 base class. When the class object is constructed, the base class is
4240 remembered. This is used for resolving attribute references: if a
4241 requested attribute is not found in the class, the search proceeds to look in the
4242 base class. This rule is applied recursively if the base class itself
4243 is derived from some other class.
4244
4245 ÅÉÉúÀඨÒåµÄÖ´Ðйý³ÌºÍ»ùÀàÊÇÒ»ÑùµÄ¡£¹¹ÔìÅÉÉúÀà¶ÔÏóʱ£¬¾Í¼ÇסÁË»ùÀà¡£ÕâÔÚ½âÎöÊôÐÔÒýÓõÄʱºòÓÈÆäÓÐÓãºÈç¹ûÔÚÀàÖÐÕÒ²»µ½ÇëÇóµ÷ÓõÄÊôÐÔ£¬¾ÍËÑË÷»ùÀà¡£Èç¹û»ùÀàÊÇÓɱðµÄÀàÅÉÉú¶øÀ´£¬Õâ¸ö¹æÔò»áµÝ¹éµÄÓ¦ÓÃÉÏÈ¥¡£
4246
4247 There's nothing special about instantiation of derived classes:
4248 \code{DerivedClassName()} creates a new instance of the class. Method
4249 references are resolved as follows: the corresponding class attribute
4250 is searched, descending down the chain of base classes if necessary,
4251 and the method reference is valid if this yields a function object.
4252
4253 ÅÉÉúÀàµÄʵÀý»¯Ã»ÓÐÊ²Ã´ÌØÊâÖ®´¦£º\code{DerivedClassName()} £¨Ê¾ÁÐÖеÄÅÉÉúÀࣩ´´½¨Ò»¸öеÄÀàʵÀý¡£·½·¨ÒýÓð´ÈçϹæÔò½âÎö£ºËÑË÷¶ÔÓ¦µÄÀàÊôÐÔ£¬±ØÒªÊ±ÑØ»ùÀàÁ´Öð¼¶ËÑË÷£¬Èç¹ûÕÒµ½Á˺¯Êý¶ÔÏóÕâ¸ö·½·¨ÒýÓþÍÊǺϷ¨µÄ
4254
4255 Derived classes may override methods of their base classes. Because
4256 methods have no special privileges when calling other methods of the
4257 same object, a method of a base class that calls another method
4258 defined in the same base class may end up calling a method of
4259 a derived class that overrides it. (For \Cpp{} programmers: all methods
4260 in Python are effectively \keyword{virtual}.)
4261
4262 ÅÉÉúÀà¿ÉÄܻḲ¸ÇÆä»ùÀàµÄ·½·¨¡£ÒòΪ·½·¨µ÷ÓÃͬһ¸ö¶ÔÏóÖÐµÄÆäËü·½·¨Ê±Ã»ÓÐÌØÈ¨£¬»ùÀàµÄ·½·¨µ÷ÓÃͬһ¸ö»ùÀàµÄ·½·¨Ê±£¬¿ÉÄÜʵ¼ÊÉÏ×îÖÕµ÷ÓÃÁËÅÉÉúÀàÖеĸ²¸Ç·½·¨¡££¨¶ÔÓÚ \Cpp{} ³ÌÐòÔ±À´Ëµ£¬PythonÖеÄËùÓз½·¨±¾ÖÊÉ϶¼ÊÇÐé·½·¨¡££©
4263
4264 An overriding method in a derived class may in fact want to extend
4265 rather than simply replace the base class method of the same name.
4266 There is a simple way to call the base class method directly: just
4267 call \samp{BaseClassName.methodname(self, arguments)}. This is
4268 occasionally useful to clients as well. (Note that this only works if
4269 the base class is defined or imported directly in the global scope.)
4270
4271 ÅÉÉúÀàÖеĸ²¸Ç·½·¨¿ÉÄÜÊÇÏëÒªÀ©³ä¶ø²»ÊǼòµ¥µÄÌæ´ú»ùÀàÖеÄÖØÃû·½·¨¡£ÓÐÒ»¸ö¼òµ¥µÄ·½·¨¿ÉÒÔÖ±½Óµ÷ÓûùÀà·½·¨£¬Ö»Òªµ÷Óãº\samp{BaseClassName.methodname(self, arguments)}¡£ÓÐʱÕâ¶ÔÓÚ¿Í»§Ò²ºÜÓÐÓᣣ¨Òª×¢ÒâµÄÖÐÖ»ÓлùÀàÔÚͬһȫ¾Ö×÷ÓÃÓò¶¨Òå»òµ¼Èëʱ²ÅÄÜÕâÑùÓᣣ©
4272
4273
4274 \subsection{Multiple Inheritance ¶à¼Ì³Ð \label{multiple}}
4275
4276 Python supports a limited form of multiple inheritance as well. A
4277 class definition with multiple base classes looks like this:
4278
4279 PythonͬÑùÓÐÏÞµÄÖ§³Ö¶à¼Ì³ÐÐÎʽ¡£¶à¼Ì³ÐµÄÀඨÒåÐÎÈçÏÂÀý£º
4280
4281 \begin{verbatim}
4282 class DerivedClassName(Base1, Base2, Base3):
4283 <statement-1>
4284 .
4285 .
4286 .
4287 <statement-N>
4288 \end{verbatim}
4289
4290 The only rule necessary to explain the semantics is the resolution
4291 rule used for class attribute references. This is depth-first,
4292 left-to-right. Thus, if an attribute is not found in
4293 \class{DerivedClassName}, it is searched in \class{Base1}, then
4294 (recursively) in the base classes of \class{Base1}, and only if it is
4295 not found there, it is searched in \class{Base2}, and so on.
4296
4297 ÕâÀïΨһÐèÒª½âÊ͵ÄÓïÒåÊǽâÎöÀàÊôÐԵĹæÔò¡£Ë³ÐòÊÇÉî¶ÈÓÅÏÈ£¬´Ó×óµ½ÓÒ¡£Òò´Ë£¬Èç¹ûÔÚ \class{DerivedClassName} £¨Ê¾ÀýÖеÄÅÉÉúÀࣩÖÐûÓÐÕÒµ½Ä³¸öÊôÐÔ£¬¾Í»áËÑË÷ \class{Base1} £¬È»ºó£¨µÝ¹éµÄ£©ËÑË÷Æä»ùÀ࣬Èç¹û×îÖÕûÓÐÕÒµ½£¬¾ÍËÑË÷ \class{Base2}£¬ÒÔ´ËÀàÍÆ¡£
4298
4299 (To some people breadth first --- searching \class{Base2} and
4300 \class{Base3} before the base classes of \class{Base1} --- looks more
4301 natural. However, this would require you to know whether a particular
4302 attribute of \class{Base1} is actually defined in \class{Base1} or in
4303 one of its base classes before you can figure out the consequences of
4304 a name conflict with an attribute of \class{Base2}. The depth-first
4305 rule makes no differences between direct and inherited attributes of
4306 \class{Base1}.)
4307
4308 £¨ÓÐЩÈËÈÏΪ¹ã¶ÈÓÅÏÈ££ÔÚËÑË÷\class{Base1}µÄ»ùÀà֮ǰËÑË÷\class{Base2}ºÍ\code{Base3}££¿´ÆðÀ´¸üΪ×ÔÈ»¡£È»¶ø£¬Èç¹û\class{Base1}ºÍ\class{Base2}Ö®¼ä·¢ÉúÁËÃüÃû³åÍ»£¬ÄãÐèÒªÁ˽âÕâ¸öÊôÐÔÊǶ¨ÒåÓÚ\class{Base1}»¹ÊÇ\class{Base1}µÄ»ùÀàÖС£¶øÉî¶ÈÓÅÏȲ»Çø·ÖÊôÐԼ̳Ð×Ô»ùÀ໹ÊÇÖ±½Ó¶¨Òå¡££©
4309
4310 It is clear that indiscriminate use of multiple inheritance is a
4311 maintenance nightmare, given the reliance in Python on conventions to
4312 avoid accidental name conflicts. A well-known problem with multiple
4313 inheritance is a class derived from two classes that happen to have a
4314 common base class. While it is easy enough to figure out what happens
4315 in this case (the instance will have a single copy of ``instance
4316 variables'' or data attributes used by the common base class), it is
4317 not clear that these semantics are in any way useful.
4318
4319 ÏÔÈ»²»¼ÓÏÞÖÆµÄʹÓöà¼Ì³Ð»á´øÀ´Î¬»¤ÉÏµÄØ¬ÃΣ¬ÒòΪ Python ÖÐÖ»ÒÀ¿¿Ô¼¶¨À´±ÜÃâÃüÃû³åÍ»¡£¶à¼Ì³ÐÒ»¸öºÜÓÐÃûµÄÎÊÌâÊÇÅÉÉú¼Ì³ÐµÄÁ½¸ö»ùÀà¶¼ÊÇ´Óͬһ¸ö»ùÀà¼Ì³Ð¶øÀ´¡£Ä¿Ç°»¹²»Çå³þÕâÔÚÓïÒåÉÏÓÐʲôÒâÒ壬Ȼ¶øºÜÈÝÒ×Ïëµ½Õâ»áÔì³Éʲôºó¹û£¨ÊµÀý»áÓÐÒ»¸ö¶ÀÁ¢µÄ¡°ÊµÀý±äÁ¿¡±»òÊý¾ÝÊôÐÔ¸´±¾×÷ÓÃÓÚ¹«¹²»ùÀà¡££©
4320
4321 %% XXX Add rules for new-style MRO?
4322
4323 \section{Private Variables ˽ÓбäÁ¿ \label{private}}
4324
4325 There is limited support for class-private
4326 identifiers. Any identifier of the form \code{__spam} (at least two
4327 leading underscores, at most one trailing underscore) is textually
4328 replaced with \code{_classname__spam}, where \code{classname} is the
4329 current class name with leading underscore(s) stripped. This mangling
4330 is done without regard to the syntactic position of the identifier, so
4331 it can be used to define class-private instance and class variables,
4332 methods, variables stored in globals, and even variables stored in instances.
4333 private to this class on instances of \emph{other} classes. Truncation
4334 may occur when the mangled name would be longer than 255 characters.
4335 Outside classes, or when the class name consists of only underscores,
4336 no mangling occurs.
4337
4338 Python ¶ÔÀàµÄ˽ÓгÉÔ±ÌṩÁËÓÐÏÞµÄÖ§³Ö¡£ÈκÎÐÎÈç \code{__spam}£¨ÒÔÖÁÉÙ˫ϻ®Ïß¿ªÍ·£¬ÖÁ¶àµ¥Ï»®Ïß½áβ£©Ëæ¼´¶¼±»Ìæ´úΪ \code{_classname__spam}£¬È¥µôǰµ¼Ï»®ÏßµÄ \code{classname} ¼´µ±Ç°µÄÀàÃû¡£ÕâÖÖ»ìÏý²»¹ØÐıêʶ·ûµÄÓ﷨λÖã¬ËùÒÔ¿ÉÓÃÀ´¶¨Òå˽ÓÐÀàʵÀýºÍÀà±äÁ¿¡¢·½·¨£¬ÒÔ¼°È«¾Ö±äÁ¿£¬ÉõÖÁÓÚ½«ÆäËüÀàµÄʵÀý±£´æÎªË½ÓбäÁ¿¡£»ìÏýÃû³¤¶È³¬¹ý255¸ö×Ö·ûµÄʱºò¿ÉÄܻᷢÉú½Ø¶Ï¡£ÔÚÀàµÄÍⲿ£¬»òÀàÃûÖ»°üº¬Ï»®Ïßʱ£¬²»»á·¢Éú½Ø¶Ï¡£
4339
4340 Name mangling is intended to give classes an easy way to define
4341 ``private'' instance variables and methods, without having to worry
4342 about instance variables defined by derived classes, or mucking with
4343 instance variables by code outside the class. Note that the mangling
4344 rules are designed mostly to avoid accidents; it still is possible for
4345 a determined soul to access or modify a variable that is considered
4346 private. This can even be useful in special circumstances, such as in
4347 the debugger, and that's one reason why this loophole is not closed.
4348 (Buglet: derivation of a class with the same name as the base class
4349 makes use of private variables of the base class possible.)
4350
4351 ÃüÃû»ìÏýÒâÔÚ¸ø³öÒ»¸öÔÚÀàÖж¨Ò塰˽ÓС±ÊµÀý±äÁ¿ºÍ·½·¨µÄ¼òµ¥Í¾¾¶£¬±ÜÃâÅÉÉúÀàµÄʵÀý±äÁ¿¶¨Òå²úÉúÎÊÌ⣬»òÕßÓëÍâ½ç´úÂëÖеıäÁ¿¸ã»ì¡£Òª×¢ÒâµÄÊÇ»ìÏý¹æÔòÖ÷ҪĿµÄÔÚÓÚ±ÜÃâÒâÍâ´íÎ󣬱»ÈÏ×÷Ϊ˽ÓеıäÁ¿ÈÔÈ»ÓпÉÄܱ»·ÃÎÊ»òÐ޸ġ£ÔÚÌØ¶¨µÄ³¡ºÏËüÒ²ÊÇÓÐÓõ쬱ÈÈçµ÷ÊÔµÄʱºò£¬ÕâÒ²ÊÇһֱûÓжÂÉÏÕâ¸ö©¶´µÄÔÒòÖ®Ò»£¨Ð¡Â©¶´£ºÅÉÉúÀàºÍ»ùÀàÈ¡ÏàͬµÄÃû×־ͿÉÒÔʹÓûùÀàµÄ˽ÓбäÁ¿¡££©
4352
4353 Notice that code passed to \code{exec}, \code{eval()} or
4354 \code{evalfile()} does not consider the classname of the invoking
4355 class to be the current class; this is similar to the effect of the
4356 \code{global} statement, the effect of which is likewise restricted to
4357 code that is byte-compiled together. The same restriction applies to
4358 \code{getattr()}, \code{setattr()} and \code{delattr()}, as well as
4359 when referencing \code{__dict__} directly.
4360
4361 ҪעÒâµÄÊÇ´«Èë \code{exec}£¬\code{eval()} »ò \code{evalfile()} µÄ´úÂë²»»á½«µ÷ÓÃËüÃǵÄÀàÊÓ×÷µ±Ç°À࣬ÕâÓë \code{global} Óï¾äµÄÇé¿öÀàËÆ£¬\code{global} µÄ×÷ÓþÖÏÞÓÚ¡°Í¬Ò»Åú¡±½øÐÐ×Ö½Ú±àÒëµÄ´úÂ롣ͬÑùµÄÏÞÖÆÒ²ÊÊÓÃÓÚ \code{getattr()}£¬\code{setattr()} ºÍ\code{delattr()}£¬ÒÔ¼°Ö±½ÓÒýÓà \code{__dict__} µÄʱºò¡£
4362
4363
4364 \section{Odds and Ends ²¹³ä \label{odds}}
4365
4366 Sometimes it is useful to have a data type similar to the Pascal
4367 ``record'' or C ``struct'', bundling together a few named data
4368 items. An empty class definition will do nicely:
4369
4370 ÓÐʱÀàËÆÓÚPascalÖС°¼Ç¼£¨record£©¡±»òCÖС°½á¹¹£¨struct£©¡±µÄÊý¾ÝÀàÐͺÜÓÐÓã¬Ëü½«Ò»×éÒÑÃüÃûµÄÊý¾ÝÏî°ó¶¨ÔÚÒ»Æð¡£Ò»¸ö¿ÕµÄÀඨÒå¿ÉÒԺܺõÄʵÏÖÕâËü£º
4371
4372 \begin{verbatim}
4373 class Employee:
4374 pass
4375
4376 john = Employee() # Create an empty employee record
4377
4378 # Fill the fields of the record
4379 john.name = 'John Doe'
4380 john.dept = 'computer lab'
4381 john.salary = 1000
4382 \end{verbatim}
4383
4384 A piece of Python code that expects a particular abstract data type
4385 can often be passed a class that emulates the methods of that data
4386 type instead. For instance, if you have a function that formats some
4387 data from a file object, you can define a class with methods
4388 \method{read()} and \method{readline()} that get the data from a string
4389 buffer instead, and pass it as an argument.% (Unfortunately, this
4390 %technique has its limitations: a class can't define operations that
4391 %are accessed by special syntax such as sequence subscripting or
4392 %arithmetic operators, and assigning such a ``pseudo-file'' to
4393 %\code{sys.stdin} will not cause the interpreter to read further input
4394 %from it.)
4395
4396 ijһ¶Î Python ´úÂëÐèÒªÒ»¸öÌØÊâµÄ³éÏóÊý¾Ý½á¹¹µÄ»°£¬Í¨³£¿ÉÒÔ´«ÈëÒ»¸öÀ࣬ÊÂʵÉÏÕâÄ£·ÂÁ˸ÃÀàµÄ·½·¨¡£ÀýÈ磬Èç¹ûÄãÓÐÒ»¸öÓÃÓÚ´ÓÎļþ¶ÔÏóÖиñʽ»¯Êý¾ÝµÄº¯Êý£¬Äã¿ÉÒÔ¶¨ÒåÒ»¸ö´øÓÐ \method{read()} ºÍ \method{readline()} ·½·¨µÄÀ࣬ÒÔ´Ë´Ó×Ö·û´®»º³å¶ÁÈ¡Êý¾Ý£¬È»ºó½«¸ÃÀàµÄ¶ÔÏó×÷Ϊ²ÎÊý´«ÈëǰÊöµÄº¯Êý¡£
4397
4398 Instance method objects have attributes, too: \code{m.im_self} is the
4399 instance object with the method \method{m}, and \code{m.im_func} is the
4400 function object corresponding to the method.
4401
4402 ʵÀý·½·¨¶ÔÏóÒ²ÓÐÊôÐÔ£º \code{m.im_self} ÊÇÒ»¸öʵÀý·½·¨ËùÊôµÄ¶ÔÏ󣬶ø \code{m.im_func} ÊÇÕâ¸ö·½·¨¶ÔÓ¦µÄº¯Êý¶ÔÏó¡£
4403
4404
4405 \section{Exceptions Are Classes Too Òì³£Ò²ÊÇÀà \label{exceptionClasses}}
4406
4407 User-defined exceptions are identified by classes as well. Using this
4408 mechanism it is possible to create extensible hierarchies of exceptions.
4409
4410 Óû§×Ô¶¨ÒåÒì³£Ò²¿ÉÒÔÊÇÀà¡£ÀûÓÃÕâ¸ö»úÖÆ¿ÉÒÔ´´½¨¿ÉÀ©Õ¹µÄÒì³£Ìåϵ¡£
4411
4412 There are two new valid (semantic) forms for the raise statement:
4413
4414 ÒÔÏÂÊÇÁ½ÖÖеÄÓÐЧ£¨ÓïÒåÉϵģ©Òì³£Å׳öÐÎʽ£º
4415
4416 \begin{verbatim}
4417 raise Class, instance
4418
4419 raise instance
4420 \end{verbatim}
4421
4422 In the first form, \code{instance} must be an instance of
4423 \class{Class} or of a class derived from it. The second form is a
4424 shorthand for:
4425
4426 µÚÒ»ÖÖÐÎʽÖУ¬\code{instance} ±ØÐëÊÇ \class{Class} »òÆäÅÉÉúÀàµÄÒ»¸öʵÀý¡£µÚ¶þÖÖÐÎʽÊÇÒÔÏÂÐÎʽµÄ¼òд£º
4427
4428 \begin{verbatim}
4429 raise instance.__class__, instance
4430 \end{verbatim}
4431
4432 A class in an except clause is compatible with an exception if it is the same
4433 class or a base class thereof (but not the other way around --- an
4434 except clause listing a derived class is not compatible with a base
4435 class). For example, the following code will print B, C, D in that
4436 order:
4437
4438 ·¢ÉúµÄÒì³£ÆäÀàÐÍÈç¹ûÊÇÒì³£×Ó¾äÖÐÁгöµÄÀ࣬»òÕßÊÇÆäÅÉÉúÀ࣬ÄÇôËüÃǾÍÊÇÏà·ûµÄ£¨·´¹ýÀ´Ëµ££·¢ÉúµÄÒì³£ÆäÀàÐÍÈç¹ûÊÇÒì³£×Ó¾äÖÐÁгöµÄÀàµÄ»ùÀ࣬ËüÃǾͲ»Ïà·û£©¡£ÀýÈ磬ÒÔÏ´úÂë»á°´Ë³Ðò´òÓ¡B£¬C£¬D£º
4439
4440 \begin{verbatim}
4441 class B:
4442 pass
4443 class C(B):
4444 pass
4445 class D(C):
4446 pass
4447
4448 for c in [B, C, D]:
4449 try:
4450 raise c()
4451 except D:
4452 print "D"
4453 except C:
4454 print "C"
4455 except B:
4456 print "B"
4457 \end{verbatim}
4458
4459 Note that if the except clauses were reversed (with
4460 \samp{except B} first), it would have printed B, B, B --- the first
4461 matching except clause is triggered.
4462
4463 ҪעÒâµÄÊÇÈç¹ûÒì³£×Ó¾äµÄ˳Ðòµßµ¹¹ýÀ´£¨ \samp{execpt B} ÔÚ×îǰ£©£¬Ëü¾Í»á´òÓ¡B£¬B£¬B££µÚÒ»¸öÆ¥ÅäµÄÒì³£±»´¥·¢¡£
4464
4465 When an error message is printed for an unhandled exception, the
4466 exception's class name is printed, then a colon and a space, and
4467 finally the instance converted to a string using the built-in function
4468 \function{str()}.
4469
4470 ´òÓ¡Ò»¸öÒì³£ÀàµÄ´íÎóÐÅϢʱ£¬ÏÈ´òÓ¡ÀàÃû£¬È»ºóÊÇÒ»¸ö¿Õ¸ñ¡¢Ò»¸öðºÅ£¬È»ºóÊÇÓÃÄÚÖú¯Êý \function{str()} ½«Ààת»»µÃµ½µÄÍêÕû×Ö·û´®¡£
4471
4472 \section{Iterators µü´úÆ÷ \label{iterators}}
4473
4474 By now you have probably noticed that most container objects can be looped
4475 over using a \keyword{for} statement:
4476
4477 ÏÖÔÚÄã¿ÉÄÜ×¢Òâµ½´ó¶àÊýÈÝÆ÷¶ÔÏ󶼿ÉÒÔÓà \code{for} ±éÀú£º
4478
4479 \begin{verbatim}
4480 for element in [1, 2, 3]:
4481 print element
4482 for element in (1, 2, 3):
4483 print element
4484 for key in {'one':1, 'two':2}:
4485 print key
4486 for char in "123":
4487 print char
4488 for line in open("myfile.txt"):
4489 print line
4490 \end{verbatim}
4491
4492 This style of access is clear, concise, and convenient. The use of iterators
4493 pervades and unifies Python. Behind the scenes, the \keyword{for}
4494 statement calls \function{iter()} on the container object. The
4495 function returns an iterator object that defines the method
4496 \method{next()} which accesses elements in the container one at a
4497 time. When there are no more elements, \method{next()} raises a
4498 \exception{StopIteration} exception which tells the \keyword{for} loop
4499 to terminate. This example shows how it all works:
4500
4501 ÕâÖÖÐÎʽµÄ·ÃÎÊÇåÎú¡¢¼ò½à¡¢·½±ã¡£µü´úÆ÷µÄÓ÷¨ÔÚ Python ÖÐÆÕ±é¶øÇÒͳһ¡£ÔÚºǫ́£¬\code{for} Óï¾äÔÚÈÝÆ÷¶ÔÏóÖе÷Óà \function{iter()} ¡£ ¸Ãº¯Êý·µ»ØÒ»¸ö¶¨ÒåÁË \method{next()} ·½·¨µÄµü´úÆ÷¶ÔÏó£¬ËüÔÚÈÝÆ÷ÖÐÖðÒ»·ÃÎÊÔªËØ¡£Ã»ÓкóÐøµÄÔªËØÊ±£¬\method{next()}Å׳öÒ»¸ö \exception{StopIteration} Ò쳣֪ͨ \code{for} Óï¾äÑ»·½áÊø¡£ÒÔÏÂÊÇÆä¹¤×÷ÔÀíµÄʾÀý£º
4502
4503 \begin{verbatim}
4504 >>> s = 'abc'
4505 >>> it = iter(s)
4506 >>> it
4507 <iterator object at 0x00A1DB50>
4508 >>> it.next()
4509 'a'
4510 >>> it.next()
4511 'b'
4512 >>> it.next()
4513 'c'
4514 >>> it.next()
4515
4516 Traceback (most recent call last):
4517 File "<stdin>", line 1, in ?
4518 it.next()
4519 StopIteration
4520 \end{verbatim}
4521
4522 Having seen the mechanics behind the iterator protocol, it is easy to add
4523 iterator behavior to your classes. Define a \method{__iter__()} method
4524 which returns an object with a \method{next()} method. If the class defines
4525 \method{next()}, then \method{__iter__()} can just return \code{self}:
4526
4527 Á˽âÁ˵ü´úÆ÷ÐÒéµÄºǫ́»úÖÆ£¬¾Í¿ÉÒÔºÜÈÝÒ׵ĸø×Ô¼ºµÄÀàÌí¼Óµü´úÆ÷ÐÐΪ¡£¶¨ÒåÒ»¸ö \method{__iter__()} ·½·¨£¬Ê¹Æä·µ»ØÒ»¸ö´øÓÐ \method{next()} ·½·¨µÄ¶ÔÏó¡£Èç¹ûÕâ¸öÀàÒѾ¶¨ÒåÁË \method{next()}£¬ÄÇô \method{__iter__()} Ö»ÐèÒª·µ»Øself£º
4528
4529 \begin{verbatim}
4530 class Reverse:
4531 "Iterator for looping over a sequence backwards"
4532 def __init__(self, data):
4533 self.data = data
4534 self.index = len(data)
4535 def __iter__(self):
4536 return self
4537 def next(self):
4538 if self.index == 0:
4539 raise StopIteration
4540 self.index = self.index - 1
4541 return self.data[self.index]
4542
4543 >>> for char in Reverse('spam'):
4544 ... print char
4545 ...
4546 m
4547 a
4548 p
4549 s
4550 \end{verbatim}
4551
4552
4553 \section{Generators Éú³ÉÆ÷ \label{generators}}
4554
4555 Generators are a simple and powerful tool for creating iterators. They are
4556 written like regular functions but use the \keyword{yield} statement whenever
4557 they want to return data. Each time \method{next()} is called, the
4558 generator resumes where it left-off (it remembers all the data values and
4559 which statement was last executed). An example shows that generators can
4560 be trivially easy to create:
4561
4562 Éú³ÉÆ÷ÊÇ´´½¨µü´úÆ÷µÄ¼òµ¥¶øÇ¿´óµÄ¹¤¾ß¡£ËüÃÇдÆðÀ´¾ÍÏñÊÇÕýÔòº¯Êý£¬ÐèÒª·µ»ØÊý¾ÝµÄʱºòʹÓà \keyword{yield} Óï¾ä¡£Ã¿´Î \method{next()} ±»µ÷ÓÃʱ£¬Éú³ÉÆ÷»Ø¸´ËüÍÑÀëµÄλÖã¨Ëü¼ÇÒäÓï¾ä×îºóÒ»´ÎÖ´ÐеÄλÖúÍËùÓеÄÊý¾ÝÖµ£©¡£ÒÔÏÂʾÀýÑÝʾÁËÉú³ÉÆ÷¿ÉÒԺܼòµ¥µÄ´´½¨³öÀ´£º
4563
4564 \begin{verbatim}
4565 def reverse(data):
4566 for index in range(len(data)-1, -1, -1):
4567 yield data[index]
4568
4569 >>> for char in reverse('golf'):
4570 ... print char
4571 ...
4572 f
4573 l
4574 o
4575 g
4576 \end{verbatim}
4577
4578 Anything that can be done with generators can also be done with class based
4579 iterators as described in the previous section. What makes generators so
4580 compact is that the \method{__iter__()} and \method{next()} methods are
4581 created automatically.
4582
4583 ǰһ½ÚÖÐÃèÊöÁË»ùÓÚÀàµÄµü´úÆ÷£¬ËüÄÜ×÷µÄÿһ¼þÊÂÉú³ÉÆ÷Ò²ÄÜ×÷µ½¡£ÒòΪ×Ô¶¯´´½¨ÁË \method{__iter__()} ºÍ \method{next()} ·½·¨£¬Éú³ÉÆ÷ÏÔµÃÈç´Ë¼ò½à¡£
4584
4585 Another key feature is that the local variables and execution state
4586 are automatically saved between calls. This made the function easier to write
4587 and much more clear than an approach using instance variables like
4588 \code{self.index} and \code{self.data}.
4589
4590 ÁíÍâÒ»¸ö¹Ø¼üµÄ¹¦ÄÜÊÇÁ½´Îµ÷ÓÃÖ®¼äµÄ¾Ö²¿±äÁ¿ºÍÖ´ÐÐÇé¿ö¶¼×Ô¶¯±£´æÁËÏÂÀ´¡£ÕâÑùº¯Êý±àдÆðÀ´¾Í±ÈÊÖ¶¯µ÷Óà \code{self.index} ºÍ \code{self.data} ÕâÑùµÄÀà±äÁ¿ÈÝÒ׵Ķࡣ
4591
4592 In addition to automatic method creation and saving program state, when
4593 generators terminate, they automatically raise \exception{StopIteration}.
4594 In combination, these features make it easy to create iterators with no
4595 more effort than writing a regular function.
4596
4597 ³ýÁË´´½¨ºÍ±£´æ³ÌÐò״̬µÄ×Ô¶¯·½·¨£¬µ±·¢ÉúÆ÷ÖÕ½áʱ£¬»¹»á×Ô¶¯Å׳ö \exception{StopIteration} Òì³£¡£×ÛÉÏËùÊö£¬ÕâЩ¹¦ÄÜʹµÃ±àдһ¸öÕýÔòº¯Êý³ÉΪ´´½¨µü´úÆ÷µÄ×î¼òµ¥·½·¨¡£
4598
4599 \section{Generator Expressions Éú³ÉÆ÷±í´ïʽ \label{genexps}}
4600
4601 Some simple generators can be coded succinctly as expressions using a syntax
4602 similar to list comprehensions but with parentheses instead of brackets. These
4603 expressions are designed for situations where the generator is used right
4604 away by an enclosing function. Generator expressions are more compact but
4605 less versatile than full generator definitions and tend to be more memory
4606 friendly than equivalent list comprehensions.
4607
4608 ÓÐʱ¼òµ¥µÄÉú³ÉÆ÷¿ÉÒÔÓüò½àµÄ·½Ê½µ÷Ó㬾ÍÏñ²»´øÖÐÀ¨ºÅµÄÁ´±íÍÆµ¼Ê½¡£ÕâЩ±í´ïʽÊÇΪ
4609 º¯Êýµ÷ÓÃÉú³ÉÆ÷¶øÉè¼ÆµÄ¡£Éú³ÉÆ÷±í´ïʽ±ÈÍêÕûµÄÉú³ÉÆ÷¶¨Òå¸ü¼ò½à£¬µ«ÊÇûÓÐÄÇô¶à±ä£¬¶øÇÒͨ³£±ÈµÈ¼ÛµÄÁ´±íÍÆµ¼Ê½¸üÈÝÒ׼ǡ£
4610
4611 Examples:
4612
4613 ÀýÈ磺
4614
4615 \begin{verbatim}
4616 >>> sum(i*i for i in range(10)) # sum of squares
4617 285
4618
4619 >>> xvec = [10, 20, 30]
4620 >>> yvec = [7, 5, 3]
4621 >>> sum(x*y for x,y in zip(xvec, yvec)) # dot product
4622 260
4623
4624 >>> from math import pi, sin
4625 >>> sine_table = dict((x, sin(x*pi/180)) for x in range(0, 91))
4626
4627 >>> unique_words = set(word for line in page for word in line.split())
4628
4629 >>> valedictorian = max((student.gpa, student.name) for student in graduates)
4630
4631 >>> data = 'golf'
4632 >>> list(data[i] for i in range(len(data)-1,-1,-1))
4633 ['f', 'l', 'o', 'g']
4634
4635 \end{verbatim}
4636
4637
4638
4639 \chapter{Brief Tour of the Standard Library ±ê×¼¿â¸ÅÀÀ \label{briefTour}}
4640
4641
4642 \section{Operating System Interface ²Ù×÷ϵͳ½Ó¿Ú \label{os-interface}}
4643
4644 The \ulink{\module{os}}{../lib/module-os.html}
4645 module provides dozens of functions for interacting with the
4646 operating system:
4647
4648 \ulink{\module{os}}{../lib/module-os.html} Ä£¿éÌṩÁ˲»ÉÙÓë²Ù×÷ϵͳÏà¹ØÁªµÄº¯Êý¡£
4649
4650 \begin{verbatim}
4651 >>> import os
4652 >>> os.system('time 0:02')
4653 0
4654 >>> os.getcwd() # Return the current working directory
4655 'C:\\Python24'
4656 >>> os.chdir('/server/accesslogs')
4657 \end{verbatim}
4658
4659 Be sure to use the \samp{import os} style instead of
4660 \samp{from os import *}. This will keep \function{os.open()} from
4661 shadowing the builtin \function{open()} function which operates much
4662 differently.
4663
4664 Ó¦¸ÃÓà \samp{import os} ·ç¸ñ¶ø·Ç \samp{from os import *}¡£ÕâÑù¿ÉÒÔ±£Ö¤Ëæ²Ù×÷ϵͳ²»Í¬¶øÓÐËù±ä»¯µÄ \function{os.open()} ²»»á¸²¸ÇÄÚÖú¯Êý \function{open()}¡£
4665
4666 \bifuncindex{help}
4667 The builtin \function{dir()} and \function{help()} functions are useful
4668 as interactive aids for working with large modules like \module{os}:
4669
4670 ÔÚʹÓÃһЩÏñ \module{os} ÕâÑùµÄ´óÐÍÄ£¿éʱÄÚÖÃµÄ \function{dir()} ºÍ \function{help()} º¯Êý·Ç³£ÓÐÓá£
4671
4672 \begin{verbatim}
4673 >>> import os
4674 >>> dir(os)
4675 <returns a list of all module functions>
4676 >>> help(os)
4677 <returns an extensive manual page created from the module's docstrings>
4678 \end{verbatim}
4679
4680 For daily file and directory management tasks, the
4681 \ulink{\module{shutil}}{../lib/module-shutil.html}
4682 module provides a higher level interface that is easier to use:
4683
4684 Õë¶ÔÈÕ³£µÄÎļþºÍĿ¼¹ÜÀíÈÎÎñ£¬\ulink{\module{shutil}}{../lib/module-shutil.html}
4685 Ä£¿éÌṩÁËÒ»¸öÒ×ÓÚʹÓõĸ߼¶½Ó¿Ú¡£
4686
4687 \begin{verbatim}
4688 >>> import shutil
4689 >>> shutil.copyfile('data.db', 'archive.db')
4690 >>> shutil.move('/build/executables', 'installdir')
4691 \end{verbatim}
4692
4693
4694 \section{File Wildcards ÎļþͨÅä·û \label{file-wildcards}}
4695
4696 The \ulink{\module{glob}}{../lib/module-glob.html}
4697 module provides a function for making file lists from directory
4698 wildcard searches:
4699
4700 \ulink{\module{glob}}{../lib/module-glob.html} Ä£¿éÌṩÁËÒ»¸öº¯ÊýÓÃÓÚ´ÓĿ¼ͨÅä·ûËÑË÷ÖÐÉú³ÉÎļþÁÐ±í¡£
4701
4702 \begin{verbatim}
4703 >>> import glob
4704 >>> glob.glob('*.py')
4705 ['primes.py', 'random.py', 'quote.py']
4706 \end{verbatim}
4707
4708
4709 \section{Command Line Arguments ÃüÁîÐвÎÊý \label{command-line-arguments}}
4710
4711 Common utility scripts often need to process command line arguments.
4712 These arguments are stored in the
4713 \ulink{\module{sys}}{../lib/module-sys.html}\ module's \var{argv}
4714 attribute as a list. For instance the following output results from
4715 running \samp{python demo.py one two three} at the command line:
4716
4717 ͨÓù¤¾ß½Å±¾¾³£µ÷ÓÃÃüÁîÐвÎÊý¡£ÕâЩÃüÁîÐвÎÊýÒÔÁ´±íÐÎʽ´æ´¢ÓÚ \ulink{\module{sys}}{../lib/module-sys.html}\ Ä£¿éµÄ \var{argv} ±äÁ¿¡£ÀýÈçÔÚÃüÁîÐÐÖÐÖ´ÐÐ \samp{python demo.py one two three} ºó¿ÉÒԵõ½ÒÔÏÂÊä³ö½á¹û£º
4718
4719 \begin{verbatim}
4720 >>> import sys
4721 >>> print sys.argv
4722 ['demo.py', 'one', 'two', 'three']
4723 \end{verbatim}
4724
4725 The \ulink{\module{getopt}}{../lib/module-getopt.html}
4726 module processes \var{sys.argv} using the conventions of the \UNIX{}
4727 \function{getopt()} function. More powerful and flexible command line
4728 processing is provided by the
4729 \ulink{\module{optparse}}{../lib/module-optparse.html} module.
4730
4731 \ulink{\module{getopt}}{../lib/module-getopt.html} Ä£¿éʹÓà \UNIX{} \function{getopt()} º¯´¦Àí \var{sys.argv}¡£¸ü¶àµÄ¸´ÔÓÃüÁîÐд¦ÀíÓÉ \ulink{\module{optparse}}{../lib/module-optparse.html} Ä£¿éÌṩ¡£
4732
4733 \section{Error Output Redirection and Program Termination ´íÎóÊä³öÖØ¶¨ÏòºÍ³ÌÐòÖÕÖ¹ \label{stderr}}
4734
4735 The \ulink{\module{sys}}{../lib/module-sys.html}
4736 module also has attributes for \var{stdin}, \var{stdout}, and
4737 \var{stderr}. The latter is useful for emitting warnings and error
4738 messages to make them visible even when \var{stdout} has been redirected:
4739
4740 \ulink{\module{sys}}{../lib/module-sys.html} »¹ÓÐ \var{stdin}£¬\var{stdout} ºÍ \var{stderr} ÊôÐÔ£¬¼´Ê¹ÔÚ \var{stdout} ±»Öض¨Ïòʱ£¬ºóÕßÒ²¿ÉÒÔÓÃÓÚÏÔʾ¾¯¸æºÍ´íÎóÐÅÏ¢¡£
4741
4742 \begin{verbatim}
4743 >>> sys.stderr.write('Warning, log file not found starting a new one\n')
4744 Warning, log file not found starting a new one
4745 \end{verbatim}
4746
4747 The most direct way to terminate a script is to use \samp{sys.exit()}.
4748
4749 ´ó¶à½Å±¾µÄ¶¨ÏòÖÕÖ¹¶¼Ê¹Óà \samp{sys.exit()}¡£
4750
4751 \section{String Pattern Matching ×Ö·û´®ÕýÔòÆ¥Åä \label{string-pattern-matching}}
4752
4753 The \ulink{\module{re}}{../lib/module-re.html}
4754 module provides regular expression tools for advanced string processing.
4755 For complex matching and manipulation, regular expressions offer succinct,
4756 optimized solutions:
4757
4758 \ulink{\module{re}}{../lib/module-re.html} Ä£¿éΪ¸ß¼¶×Ö·û´®´¦ÀíÌṩÁËÕýÔò±í´ïʽ¹¤¾ß¡£¶ÔÓÚ¸´Ôӵį¥ÅäºÍ´¦Àí£¬ÕýÔò±í´ïʽÌṩÁ˼ò½à¡¢ÓÅ»¯µÄ½â¾ö·½°¸¡£
4759
4760 \begin{verbatim}
4761 >>> import re
4762 >>> re.findall(r'\bf[a-z]*', 'which foot or hand fell fastest')
4763 ['foot', 'fell', 'fastest']
4764 >>> re.sub(r'(\b[a-z]+) \1', r'\1', 'cat in the the hat')
4765 'cat in the hat'
4766 \end{verbatim}
4767
4768 When only simple capabilities are needed, string methods are preferred
4769 because they are easier to read and debug:
4770
4771 Èç¹ûÖ»ÐèÒª¼òµ¥µÄ¹¦ÄÜ£¬Ó¦¸ÃÊ×ÏÈ¿¼ÂÇ×Ö·û´®·½·¨£¬ÒòΪËüÃǷdz£¼òµ¥£¬Ò×ÓÚÔĶÁºÍµ÷ÊÔ¡£
4772
4773 \begin{verbatim}
4774 >>> 'tea for too'.replace('too', 'two')
4775 'tea for two'
4776 \end{verbatim}
4777
4778 \section{Mathematics Êýѧ \label{mathematics}}
4779
4780 The \ulink{\module{math}}{../lib/module-math.html} module gives
4781 access to the underlying C library functions for floating point math:
4782
4783 \ulink{\module{math}}{../lib/module-math.html} Ä£¿éΪ¸¡µãÔËËãÌṩÁ˶ԵײãCº¯Êý¿âµÄ·ÃÎÊ¡£
4784
4785 \begin{verbatim}
4786 >>> import math
4787 >>> math.cos(math.pi / 4.0)
4788 0.70710678118654757
4789 >>> math.log(1024, 2)
4790 10.0
4791 \end{verbatim}
4792
4793 The \ulink{\module{random}}{../lib/module-random.html}
4794 module provides tools for making random selections:
4795
4796 \ulink{\module{random}}{../lib/module-random.html} ÌṩÁËÉú³ÉËæ»úÊýµÄ¹¤¾ß¡£
4797
4798 \begin{verbatim}
4799 >>> import random
4800 >>> random.choice(['apple', 'pear', 'banana'])
4801 'apple'
4802 >>> random.sample(xrange(100), 10) # sampling without replacement
4803 [30, 83, 16, 4, 8, 81, 41, 50, 18, 33]
4804 >>> random.random() # random float
4805 0.17970987693706186
4806 >>> random.randrange(6) # random integer chosen from range(6)
4807 4
4808 \end{verbatim}
4809
4810
4811 \section{Internet Access »¥ÁªÍø·ÃÎÊ \label{internet-access}}
4812
4813 There are a number of modules for accessing the internet and processing
4814 internet protocols. Two of the simplest are
4815 \ulink{\module{urllib2}}{../lib/module-urllib2.html}
4816 for retrieving data from urls and
4817 \ulink{\module{smtplib}}{../lib/module-smtplib.html}
4818 for sending mail:
4819
4820 Óм¸¸öÄ£¿éÓÃÓÚ·ÃÎÊ»¥ÁªÍøÒÔ¼°´¦ÀíÍøÂçͨÐÅÐÒé¡£ÆäÖÐ×î¼òµ¥µÄÁ½¸öÊÇÓÃÓÚ´¦Àí´Ó urls ½ÓÊÕµÄÊý¾ÝµÄ \ulink{\module{urllib2}}{../lib/module-urllib2.html} ÒÔ¼°ÓÃÓÚ·¢Ë͵ç×ÓÓʼþµÄ \ulink{\module{smtplib}}{../lib/module-smtplib.html}¡£
4821
4822 \begin{verbatim}
4823 >>> import urllib2
4824 >>> for line in urllib2.urlopen('http://tycho.usno.navy.mil/cgi-bin/timer.pl'):
4825 ... if 'EST' in line or 'EDT' in line: # look for Eastern Time
4826 ... print line
4827
4828 <BR>Nov. 25, 09:43:32 PM EST
4829
4830 >>> import smtplib
4831 >>> server = smtplib.SMTP('localhost')
4832 >>> server.sendmail('[email protected]', '[email protected]',
4833 """To: [email protected]
4834 From: [email protected]
4835
4836 Beware the Ides of March.
4837 """)
4838 >>> server.quit()
4839 \end{verbatim}
4840
4841
4842 \section{Dates and Times ÈÕÆÚºÍʱ¼ä \label{dates-and-times}}
4843
4844 The \ulink{\module{datetime}}{../lib/module-datetime.html} module
4845 supplies classes for manipulating dates and times in both simple
4846 and complex ways. While date and time arithmetic is supported, the
4847 focus of the implementation is on efficient member extraction for
4848 output formatting and manipulation. The module also supports objects
4849 that are timezone aware.
4850
4851 \ulink{\module{datetime}}{../lib/module-datetime.html} Ä£¿éΪÈÕÆÚºÍʱ¼ä´¦ÀíͬʱÌṩÁ˼òµ¥ºÍ¸´Ôӵķ½·¨¡£Ö§³ÖÈÕÆÚºÍʱ¼äËã·¨µÄͬʱ£¬ÊµÏÖµÄÖØµã·ÅÔÚ¸üÓÐЧµÄ´¦ÀíºÍ¸ñʽ»¯Êä³ö¡£¸ÃÄ£¿é»¹Ö§³ÖÊ±Çø´¦Àí¡£
4852
4853 \begin{verbatim}
4854 # dates are easily constructed and formatted
4855 >>> from datetime import date
4856 >>> now = date.today()
4857 >>> now
4858 datetime.date(2003, 12, 2)
4859 >>> now.strftime("%m-%d-%y. %d %b %Y is a %A on the %d day of %B.")
4860 '12-02-03. 02 Dec 2003 is a Tuesday on the 02 day of December.'
4861
4862 # dates support calendar arithmetic
4863 >>> birthday = date(1964, 7, 31)
4864 >>> age = now - birthday
4865 >>> age.days
4866 14368
4867 \end{verbatim}
4868
4869
4870 \section{Data Compression Êý¾ÝѹËõ \label{data-compression}}
4871
4872 Common data archiving and compression formats are directly supported
4873 by modules including:
4874 \ulink{\module{zlib}}{../lib/module-zlib.html},
4875 \ulink{\module{gzip}}{../lib/module-gzip.html},
4876 \ulink{\module{bz2}}{../lib/module-bz2.html},
4877 \ulink{\module{zipfile}}{../lib/module-zipfile.html}, and
4878 \ulink{\module{tarfile}}{../lib/module-tarfile.html}.
4879
4880 ÒÔÏÂÄ£¿éÖ±½ÓÖ§³ÖͨÓõÄÊý¾Ý´ò°üºÍѹËõ¸ñʽ£º
4881
4882 \ulink{\module{zlib}}{../lib/module-zlib.html}£¬
4883 \ulink{\module{gzip}}{../lib/module-gzip.html}£¬
4884 \ulink{\module{bz2}}{../lib/module-bz2.html}£¬
4885 \ulink{\module{zipfile}}{../lib/module-zipfile.html}£¬ ÒÔ¼°
4886 \ulink{\module{tarfile}}{../lib/module-tarfile.html}
4887
4888 \begin{verbatim}
4889 >>> import zlib
4890 >>> s = 'witch which has which witches wrist watch'
4891 >>> len(s)
4892 41
4893 >>> t = zlib.compress(s)
4894 >>> len(t)
4895 37
4896 >>> zlib.decompress(t)
4897 'witch which has which witches wrist watch'
4898 >>> zlib.crc32(s)
4899 226805979
4900 \end{verbatim}
4901
4902
4903 \section{Performance Measurement ÐÔÄܶÈÁ¿ \label{performance-measurement}}
4904
4905 Some Python users develop a deep interest in knowing the relative
4906 performance of different approaches to the same problem.
4907 Python provides a measurement tool that answers those questions
4908 immediately.
4909
4910 ÓÐЩÓû§¶ÔÁ˽â½â¾öͬһÎÊÌâµÄ²»Í¬·½·¨Ö®¼äµÄÐÔÄܲîÒìºÜ¸ÐÐËȤ¡£Python ÌṩÁËÒ»¸ö¶ÈÁ¿¹¤¾ß£¬ÎªÕâЩÎÊÌâÌṩÁËÖ±½Ó´ð°¸¡£
4911
4912 For example, it may be tempting to use the tuple packing and unpacking
4913 feature instead of the traditional approach to swapping arguments.
4914 The \ulink{\module{timeit}}{../lib/module-timeit.html} module
4915 quickly demonstrates a modest performance advantage:
4916
4917 ÀýÈ磬ʹÓÃÔª×é·â×°ºÍ²ð·âÀ´½»»»ÔªËØ¿´ÆðÀ´Òª±ÈʹÓô«Í³µÄ·½·¨ÒªÓÕÈ˵Ķࡣ\ulink{\module{timeit}}{../lib/module-timeit.html}
4918 ºÜ·½±ãµÄÑéÖ¤ÁË×îеÄÐÔÄÜÓÅ»¯¡£
4919
4920 \begin{verbatim}
4921 >>> from timeit import Timer
4922 >>> Timer('t=a; a=b; b=t', 'a=1; b=2').timeit()
4923 0.57535828626024577
4924 >>> Timer('a,b = b,a', 'a=1; b=2').timeit()
4925 0.54962537085770791
4926 \end{verbatim}
4927
4928 In contrast to \module{timeit}'s fine level of granularity, the
4929 \ulink{\module{profile}}{../lib/module-profile.html} and \module{pstats}
4930 modules provide tools for identifying time critical sections in larger blocks
4931 of code.
4932
4933 Ïà¶ÔÓÚ \module{timeit} µÄϸÁ£¶È£¬\ulink{\module{profile}}{../lib/module-profile.html} ºÍ \module{pstats} Ä£¿éÌṩÁËÕë¶Ô¸ü´ó´úÂë¿éµÄʱ¼ä¶ÈÁ¿¹¤¾ß¡£
4934
4935 \section{Quality Control ÖÊÁ¿¿ØÖÆ \label{quality-control}}
4936
4937 One approach for developing high quality software is to write tests for
4938 each function as it is developed and to run those tests frequently during
4939 the development process.
4940
4941 ¿ª·¢¸ßÖÊÁ¿Èí¼þµÄ·½·¨Ö®Ò»ÊÇΪÿһ¸öº¯Êý¿ª·¢²âÊÔ´úÂ룬²¢ÇÒÔÚ¿ª·¢¹ý³ÌÖо³£½øÐвâÊÔ¡£
4942
4943 The \ulink{\module{doctest}}{../lib/module-doctest.html} module provides
4944 a tool for scanning a module and validating tests embedded in a program's
4945 docstrings. Test construction is as simple as cutting-and-pasting a
4946 typical call along with its results into the docstring. This improves
4947 the documentation by providing the user with an example and it allows the
4948 doctest module to make sure the code remains true to the documentation:
4949
4950 \ulink{\module{doctest}}{../lib/module-doctest.html} Ä£¿éÌṩÁËÒ»¸ö¹¤¾ß£¬É¨ÃèÄ£¿é²¢¸ù¾Ý³ÌÐòÖÐÄÚǶµÄÎĵµ×Ö·û´®Ö´ÐвâÊÔ¡£²âÊÔ¹¹ÔìÈçͬ¼òµ¥µÄ½«ËüµÄÊä³ö½á¹û¼ôÇв¢Õ³Ìùµ½Îĵµ×Ö·û´®ÖС£Í¨¹ýÓû§ÌṩµÄÀý×Ó£¬Ëü·¢Õ¹ÁËÎĵµ£¬ÔÊÐí doctest Ä£¿éÈ·ÈÏ´úÂëµÄ½á¹ûÊÇ·ñÓëÎĵµÒ»Ö¡£
4951
4952 \begin{verbatim}
4953 def average(values):
4954 """Computes the arithmetic mean of a list of numbers.
4955
4956 >>> print average([20, 30, 70])
4957 40.0
4958 """
4959 return sum(values, 0.0) / len(values)
4960
4961 import doctest
4962 doctest.testmod() # automatically validate the embedded tests
4963 \end{verbatim}
4964
4965 The \ulink{\module{unittest}}{../lib/module-unittest.html} module is not
4966 as effortless as the \module{doctest} module, but it allows a more
4967 comprehensive set of tests to be maintained in a separate file:
4968
4969 \ulink{\module{unittest}}{../lib/module-unittest.html} Ä£¿é²»Ïñ \module{doctest} Ä£¿éÄÇôÈÝÒ×ʹÓ㬲»¹ýËü¿ÉÒÔÔÚÒ»¸ö¶ÀÁ¢µÄÎļþÀïÌṩһ¸ö¸üÈ«ÃæµÄ²âÊÔ¼¯¡£
4970
4971 \begin{verbatim}
4972 import unittest
4973
4974 class TestStatisticalFunctions(unittest.TestCase):
4975
4976 def test_average(self):
4977 self.assertEqual(average([20, 30, 70]), 40.0)
4978 self.assertEqual(round(average([1, 5, 7]), 1), 4.3)
4979 self.assertRaises(ZeroDivisionError, average, [])
4980 self.assertRaises(TypeError, average, 20, 30, 70)
4981
4982 unittest.main() # Calling from the command line invokes all tests
4983 \end{verbatim}
4984
4985 \section{Batteries Included\label{batteries-included}}
4986
4987 Python has a ``batteries included'' philosophy. This is best seen
4988 through the sophisticated and robust capabilities of its larger
4989 packages. For example:
4990
4991 Python ÌåÏÖÁË¡°batteries included¡±ÕÜѧ¡£Python ¿ÉÒÔͨ¹ý¸ü´óµÄ°üµÄÀ´µÃµ½Ó¦¸¶¸÷ÖÖ¸´ÔÓÇé¿öµÄÇ¿´óÄÜÁ¦£¬´ÓÕâÒ»µãÎÒÃÇ¿ÉÒÔ¿´³ö¸Ã˼ÏëµÄÓ¦Óá£ÀýÈ磺
4992
4993 \begin{itemize}
4994 \item The \ulink{\module{xmlrpclib}}{../lib/module-xmlrpclib.html} and
4995 \ulink{\module{SimpleXMLRPCServer}}{../lib/module-SimpleXMLRPCServer.html}
4996 modules make implementing remote procedure calls into an almost trivial task.
4997 Despite the modules names, no direct knowledge or handling of XML is needed.
4998
4999 \ulink{\module{xmlrpclib}}{../lib/module-xmlrpclib.html} ºÍ \ulink{\module{SimpleXMLRPCServer}}{../lib/module-SimpleXMLRPCServer.html} Ä£¿éʵÏÖÁËÔÚËöËéµÄÈÎÎñÖе÷ÓÃÔ¶³Ì¹ý³Ì¡£¾¡¹ÜÓÐÕâÑùµÄÃû×Ö£¬ÆäʵÓû§²»ÐèÒªÖ±½Ó´¦Àí
5000 XML £¬Ò²²»ÐèÒªÕâ·½ÃæµÄ֪ʶ¡£
5001 \item The \ulink{\module{email}}{../lib/module-email.html} package is a library
5002 for managing email messages, including MIME and other RFC 2822-based message
5003 documents. Unlike \module{smtplib} and \module{poplib} which actually send
5004 and receive messages, the email package has a complete toolset for building
5005 or decoding complex message structures (including attachments) and for
5006 implementing internet encoding and header protocols.
5007
5008 \ulink{\module{email}}{../lib/module-email.html} °üÊÇÒ»¸öÓʼþÏûÏ¢¹ÜÀí¿â£¬¿ÉÒÔ´¦Àí MIME »òÆäËü»ùÓÚ RFC 2822 µÄÏûÏ¢Îĵµ¡£²»Í¬ÓÚʵ¼Ê·¢ËͺͽÓÊÕÏûÏ¢µÄ \module{smtplib} ºÍ \module{poplib} Ä£¿é£¬email °üÓÐÒ»¸öÓÃÓÚ¹¹½¨»ò½âÎö¸´ÔÓÏûÏ¢½á¹¹£¨°üÀ¨¸½¼þ£©ÒÔ¼°ÊµÏÖ»¥ÁªÍø±àÂëºÍÍ·ÐÒéµÄÍêÕû¹¤¾ß¼¯¡£
5009 \item The \ulink{\module{xml.dom}}{../lib/module-xml.dom.html} and
5010 \ulink{\module{xml.sax}}{../lib/module-xml.sax.html} packages provide robust
5011 support for parsing this popular data interchange format. Likewise, the
5012 \ulink{\module{csv}}{../lib/module-csv.html} module supports direct reads and
5013 writes in a common database format. Together, these modules and packages
5014 greatly simplify data interchange between python applications and other
5015 tools.
5016
5017 \ulink{\module{xml.dom}}{../lib/module-xml.dom.html} ºÍ \ulink{\module{xml.sax}}{../lib/module-xml.sax.html} °üΪÁ÷ÐеÄÐÅÏ¢½»»»¸ñʽÌṩÁËÇ¿´óµÄÖ§³Ö¡£Í¬Ñù£¬ \module{csv} Ä£¿éÖ§³ÖÔÚͨÓÃÊý¾Ý¿â¸ñʽÖÐÖ±½Ó¶Áд¡£×ÛºÏÆðÀ´£¬ÕâЩģ¿éºÍ°ü´ó´ó¼ò»¯ÁË
5018 Python Ó¦ÓóÌÐòºÍÆäËü¹¤¾ßÖ®¼äµÄÊý¾Ý½»»»¡£
5019 \item Internationalization is supported by a number of modules including
5020 \ulink{\module{gettext}}{../lib/module-gettext.html},
5021 \ulink{\module{locale}}{../lib/module-locale.html}, and the
5022 \ulink{\module{codecs}}{../lib/module-codecs.html} package.
5023
5024 ¹ú¼Ê»¯ÓÉ \ulink{\module{gettext}}{../lib/module-gettext.html}£¬
5025 \ulink{\module{locale}}{../lib/module-locale.html}ºÍ
5026 \ulink{\module{codecs}}{../lib/module-codecs.html} °üÖ§³Ö
5027 \end{itemize}
5028
5029 \chapter{Brief Tour of the Standard Library -- Part II ±ê×¼¿â¸ÅÀÀ \label{briefTourTwo}}
5030
5031 This second tour covers more advanced modules that support professional
5032 programming needs. These modules rarely occur in small scripts.
5033
5034 µÚ¶þ²¿·Ö°üº¬ÁËÖ§³Öרҵ±à³Ì¹¤×÷ËùÐèµÄ¸ü¸ß¼¶µÄÄ£¿é£¬ÕâЩģ¿éºÜÉÙ³öÏÖÔÚС½Å±¾ÖС£
5035
5036 \section{Output Formatting ¸ñʽ»¯Êä³ö \label{output-formatting}}
5037
5038 The \ulink{\module{repr}}{../lib/module-repr.html} module provides a
5039 version of \function{repr()} customized for abbreviated displays of large
5040 or deeply nested containers:
5041
5042
5043 \begin{verbatim}
5044 >>> import repr
5045 >>> repr.repr(set('supercalifragilisticexpialidocious'))
5046 "set(['a', 'c', 'd', 'e', 'f', 'g', ...])"
5047 \end{verbatim}
5048
5049 The \ulink{\module{pprint}}{../lib/module-pprint.html} module offers
5050 more sophisticated control over printing both built-in and user defined
5051 objects in a way that is readable by the interpreter. When the result
5052 is longer than one line, the ``pretty printer'' adds line breaks and
5053 indentation to more clearly reveal data structure:
5054
5055 The \ulink{\module{pprint}}{../lib/module-pprint.html} Ä£¿é¸øÀÏÊÖÌṩÁËÒ»ÖÖ½âÊÍÆ÷¿É¶ÁµÄ·½Ê½ÉîÈë¿ØÖÆÄÚÖúÍÓû§×Ô¶¨Òå¶ÔÏóµÄ´òÓ¡¡£µ±Êä³ö³¬¹ýÒ»ÐеÄʱºò£¬¡°ÃÀ»¯´òÓ¡£¨pretty printer£©¡±Ìí¼Ó¶ÏÐкͱêʶ·û£¬Ê¹µÃÊý¾Ý½á¹¹ÏÔʾµÄ¸üÇåÎú£º
5056
5057 \begin{verbatim}
5058 >>> import pprint
5059 >>> t = [[[['black', 'cyan'], 'white', ['green', 'red']], [['magenta',
5060 ... 'yellow'], 'blue']]]
5061 ...
5062 >>> pprint.pprint(t, width=30)
5063 [[[['black', 'cyan'],
5064 'white',
5065 ['green', 'red']],
5066 [['magenta', 'yellow'],
5067 'blue']]]
5068 \end{verbatim}
5069
5070 The \ulink{\module{textwrap}}{../lib/module-textwrap.html} module
5071 formats paragraphs of text to fit a given screen width:
5072
5073 The \ulink{\module{textwrap}}{../lib/module-textwrap.html} Ä£¿é¸ñʽ»¯Îı¾¶ÎÂäÒÔÊÊÓ¦É趨µÄÆÁ¿í£º
5074
5075 \begin{verbatim}
5076 >>> import textwrap
5077 >>> doc = """The wrap() method is just like fill() except that it returns
5078 ... a list of strings instead of one big string with newlines to separate
5079 ... the wrapped lines."""
5080 ...
5081 >>> print textwrap.fill(doc, width=40)
5082 The wrap() method is just like fill()
5083 except that it returns a list of strings
5084 instead of one big string with newlines
5085 to separate the wrapped lines.
5086 \end{verbatim}
5087
5088 The \ulink{\module{locale}}{../lib/module-locale.html} module accesses
5089 a database of culture specific data formats. The grouping attribute
5090 of locale's format function provides a direct way of formatting numbers
5091 with group separators:
5092
5093 The \ulink{\module{locale}}{../lib/module-locale.html} Ä£¿é°´·ÃÎÊÔ¤¶¨ºÃµÄ¹ú¼ÒÐÅÏ¢Êý¾Ý¿â¡£localeµÄ¸ñʽ»¯º¯ÊýÊôÐÔ¼¯ÌṩÁËÒ»¸öÖ±½Ó·½Ê½ÒÔ·Ö×é±êʾ¸ñʽ»¯Êý×Ö£º
5094
5095 \begin{verbatim}
5096 >>> import locale
5097 >>> locale.setlocale(locale.LC_ALL, 'English_United States.1252')
5098 'English_United States.1252'
5099 >>> conv = locale.localeconv() # get a mapping of conventions
5100 >>> x = 1234567.8
5101 >>> locale.format("%d", x, grouping=True)
5102 '1,234,567'
5103 >>> locale.format("%s%.*f", (conv['currency_symbol'],
5104 ... conv['frac_digits'], x), grouping=True)
5105 '$1,234,567.80'
5106 \end{verbatim}
5107
5108
5109 \section{Templating Ä£°æ \label{templating}}
5110
5111 The \ulink{\module{string}}{../lib/module-string.html} module includes a
5112 versatile \class{Template} class with a simplified syntax suitable for
5113 editing by end-users. This allows users to customize their applications
5114 without having to alter the application.
5115
5116 \ulink{\module{string}}{../lib/module-string.html} ÌṩÁËÒ»¸öÁé»î¶à±äµÄÄ£°æÀà \class{template}£¬Ê¹ÓÃËü×îÖÕÓû§¿ÉÒÔÓüòµ¥µÄ½øÐб༡£ÕâʹÓû§¿ÉÒÔÔÚ²»½øÐиıäµÄÇé¿ö϶¨ÖÆËûÃǵÄÓ¦ÓóÌÐò¡£
5117
5118 The format uses placeholder names formed by \samp{\$} with valid Python
5119 identifiers (alphanumeric characters and underscores). Surrounding the
5120 placeholder with braces allows it to be followed by more alphanumeric letters
5121 with no intervening spaces. Writing \samp{\$\$} creates a single escaped
5122 \samp{\$}:
5123
5124 ¸ñʽʹÓà \samp{\$} Ϊ¿ªÍ·µÄ Python ºÏ·¨±êʶ£¨Êý×Ö¡¢×ÖĸºÍÏ»®Ïߣ©×÷Ϊռλ·û¡£Õ¼Î»·ûÍâÃæµÄ´óÀ¨ºÅʹËü¿ÉÒÔºÍÆäËüµÄ×Ö·û²»¼Ó¿Õ¸ñ»ìÔÚÒ»Æð¡£ \samp{\$\$} ´´½¨Ò»¸öµ¥¶ÀµÄ \samp{\$}¡£
5125
5126 \begin{verbatim}
5127 >>> from string import Template
5128 >>> t = Template('${village}folk send $$10 to $cause.')
5129 >>> t.substitute(village='Nottingham', cause='the ditch fund')
5130 'Nottinghamfolk send $10 to the ditch fund.'
5131 \end{verbatim}
5132
5133 The \method{substitute} method raises a \exception{KeyError} when a
5134 placeholder is not supplied in a dictionary or a keyword argument. For
5135 mail-merge style applications, user supplied data may be incomplete and the
5136 \method{safe_substitute} method may be more appropriate --- it will leave
5137 placeholders unchanged if data is missing:
5138
5139 ×Öµä»òÕ߹ؼü×Ö²ÎÊýÖÐȱÉÙij¸öռλ·ûµÄʱºò \method{substitute} ·½·¨Å׳ö \exception{KeyError} Òì³£¡£ÔÚÓʼþ-ºÏ²¢·ç¸ñµÄÓ¦ÓóÌÐòÖУ¬Óû§ÌṩµÄÊý¾Ý¿ÉÄܲ¢²»ÍêÕû£¬Ò²ÐíÓà \method{safe-substitute} ·½·¨¸üºÏÊÊ¡ª¡ªÈç¹ûÊý¾Ý²»ÍêÕû£¬Ëü±£Áôδ¸Ä¶¯µÄռλ·û£º
5140
5141 \begin{verbatim}
5142 >>> t = Template('Return the $item to $owner.')
5143 >>> d = dict(item='unladen swallow')
5144 >>> t.substitute(d)
5145 Traceback (most recent call last):
5146 . . .
5147 KeyError: 'owner'
5148 >>> t.safe_substitute(d)
5149 'Return the unladen swallow to $owner.'
5150 \end{verbatim}
5151
5152 Template subclasses can specify a custom delimiter. For example, a batch
5153 renaming utility for a photo browser may elect to use percent signs for
5154 placeholders such as the current date, image sequence number, or file format:
5155
5156 Ä£°æ×ÓÀà¿ÉÒÔÖ¸¶¨Ò»¸ö¶¨ÖÆ·Ö¸ô·û¡£ÀýÈ磬ͼÏñä¯ÀÀÆ÷µÄÅúÁ¿ÃüÃû¹¤¾ß¿ÉÄÜÑ¡ÓðٷֺÅ×÷Ϊ±íʾµ±Ç°ÈÕÆÚ¡¢Í¼ÏñÐòÁкŻòÎļþ¸ñʽµÄռλ·û£º
5157
5158 \begin{verbatim}
5159 >>> import time, os.path
5160 >>> photofiles = ['img_1074.jpg', 'img_1076.jpg', 'img_1077.jpg']
5161 >>> class BatchRename(Template):
5162 ... delimiter = '%'
5163 >>> fmt = raw_input('Enter rename style (%d-date %n-seqnum %f-format): ')
5164 Enter rename style (%d-date %n-seqnum %f-format): Ashley_%n%f
5165
5166 >>> t = BatchRename(fmt)
5167 >>> date = time.strftime('%d%b%y')
5168 >>> for i, filename in enumerate(photofiles):
5169 ... base, ext = os.path.splitext(filename)
5170 ... newname = t.substitute(d=date, n=i, f=ext)
5171 ... print '%s --> %s' % (filename, newname)
5172
5173 img_1074.jpg --> Ashley_0.jpg
5174 img_1076.jpg --> Ashley_1.jpg
5175 img_1077.jpg --> Ashley_2.jpg
5176 \end{verbatim}
5177
5178 Another application for templating is separating program logic from the
5179 details of multiple output formats. This makes it possible to substitute
5180 custom templates for XML files, plain text reports, and HTML web reports.
5181
5182 ÁíÒ»¸öÓ¦ÓÃÊǽ«¶àÑù»¯µÄÊä³ö¸ñʽϸ½Ú´Ó³ÌÐòÂß¼ÖзÖÀë³öÀ´¡£ÕâʹµÃΪ XML Îļþ£¬´¿Îı¾±¨±í£¬HTML web ±¨±í¶¨ÖÆÌ滻ģ°æ³ÉΪ¿ÉÄÜ¡£
5183
5184 \section{Working with Binary Data Record Layouts ʹÓöþ½øÖƼǼ²ã \label{binary-formats}}
5185
5186 The \ulink{\module{struct}}{../lib/module-struct.html} module provides
5187 \function{pack()} and \function{unpack()} functions for working with
5188 variable length binary record formats. The following example shows how
5189 to loop through header information in a ZIP file (with pack codes
5190 \code{"H"} and \code{"L"} representing two and four byte unsigned
5191 numbers respectively):
5192
5193 \ulink{\module{struct}}{../lib/module-struct.html} Ä£¿éÌṩ \function{pack()} ºÍ \function{unpack()} º¯ÊýÓÃÓڱ䳤¶þ½øÖƼǼ¸ñʽ¡£ÒÔÏÂʾÀýÏÔʾÁËÈçºÎͨ¹ýZIPÎļþµÄÍ·ÐÅÏ¢£¨Ñ¹Ëõ´úÂëÖÐµÄ \code{"H"} ºÍ \code{"L"} ·Ö±ð´«µÝ¶þºÍËÄ×Ö½ÚÎÞ·ûºÅÕûÊý£©¡£
5194
5195 \begin{verbatim}
5196 import struct
5197
5198 data = open('myfile.zip', 'rb').read()
5199 start = 0
5200 for i in range(3): # show the first 3 file headers
5201 start += 14
5202 fields = struct.unpack('LLLHH', data[start:start+16])
5203 crc32, comp_size, uncomp_size, filenamesize, extra_size = fields
5204
5205 start += 16
5206 filename = data[start:start+filenamesize]
5207 start += filenamesize
5208 extra = data[start:start+extra_size]
5209 print filename, hex(crc32), comp_size, uncomp_size
5210
5211 start += extra_size + comp_size # skip to the next header
5212 \end{verbatim}
5213
5214
5215 \section{Multi-threading ¶àÏß³Ì \label{multi-threading}}
5216
5217 Threading is a technique for decoupling tasks which are not sequentially
5218 dependent. Threads can be used to improve the responsiveness of
5219 applications that accept user input while other tasks run in the
5220 background. A related use case is running I/O in parallel with
5221 computations in another thread.
5222
5223 Ïß³ÌÊÇÒ»¸ö·ÖÀëÎÞ˳ÐòÒÀÀµ¹ØÏµÈÎÎñµÄ¼¼Êõ¡£ÔÚijЩÈÎÎñÔËÐÐÓÚºǫ́µÄʱºòÓ¦ÓóÌÐò»á±äµÃ³Ù»º£¬Ï߳̿ÉÒÔÌáÉýÆäËÙ¶È¡£Ò»¸öÓйصÄÓÃ;ÊÇÔÚI/OµÄͬʱÆäËüÏ߳̿ÉÒÔ²¢ÐмÆËã¡£
5224
5225 The following code shows how the high level
5226 \ulink{\module{threading}}{../lib/module-threading.html} module can run
5227 tasks in background while the main program continues to run:
5228
5229 ÏÂÃæµÄ´úÂëÏÔʾÁ˸߼¶Ä£¿é \ulink{\module{threading}}{../lib/module-threading.html} ÈçºÎÔÚÖ÷³ÌÐòÔËÐеÄͬʱÔËÐÐÈÎÎñ¡£
5230
5231 \begin{verbatim}
5232 import threading, zipfile
5233
5234 class AsyncZip(threading.Thread):
5235 def __init__(self, infile, outfile):
5236 threading.Thread.__init__(self)
5237 self.infile = infile
5238 self.outfile = outfile
5239 def run(self):
5240 f = zipfile.ZipFile(self.outfile, 'w', zipfile.ZIP_DEFLATED)
5241 f.write(self.infile)
5242 f.close()
5243 print 'Finished background zip of: ', self.infile
5244
5245 background = AsyncZip('mydata.txt', 'myarchive.zip')
5246 background.start()
5247 print 'The main program continues to run in foreground.'
5248
5249 background.join() # Wait for the background task to finish
5250 print 'Main program waited until background was done.'
5251 \end{verbatim}
5252
5253 The principal challenge of multi-threaded applications is coordinating
5254 threads that share data or other resources. To that end, the threading
5255 module provides a number of synchronization primitives including locks,
5256 events, condition variables, and semaphores.
5257
5258 ¶àÏß³ÌÓ¦ÓóÌÐò×îÖØÒªµÄÌôÕ½ÊÇÔÚе÷Ï̹߳²ÏíµÄÊý¾ÝºÍÆäËü×ÊÔ´¡£×îÖÕ£¬Ïß³ÌÄ£¿éÌṩÁ˼¸¸ö»ù±¾µÄͬ²½·½Ê½ÈçËø¡¢Ê¼þ£¬Ìõ¼þ±äÁ¿ºÍÆìÓï¡£
5259
5260 While those tools are powerful, minor design errors can result in
5261 problems that are difficult to reproduce. So, the preferred approach
5262 to task coordination is to concentrate all access to a resource
5263 in a single thread and then use the
5264 \ulink{\module{Queue}}{../lib/module-Queue.html} module to feed that
5265 thread with requests from other threads. Applications using
5266 \class{Queue} objects for inter-thread communication and coordination
5267 are easier to design, more readable, and more reliable.
5268
5269 ¾¡¹Ü¹¤¾ßºÜÇ¿´ó£¬Î¢Ð¡µÄÉè¼Æ´íÎóÒ²¿ÉÄÜÔì³ÉÄÑÒÔÍì»ØµÄ¹ÊÕÏ¡£Òò´Ë£¬¸üºÃµÄ·½·¨Êǽ«ËùÓеÄ×ÊÔ´·ÃÎʼ¯Öе½Ò»¸ö¶ÀÁ¢µÄÏß³ÌÖУ¬È»ºóʹÓà \ulink{\module{Queue}}{../lib/module-Queue.html} Ä£¿éµ÷¶È¸ÃÏß³ÌÏàÓ¦ÆäËüÏ̵߳ÄÇëÇó¡£Ó¦ÓóÌÐòʹÓà \class{Queue} ¶ÔÏó¿ÉÒÔÈÃÄÚ²¿Ïß³ÌͨÐźÍе÷¸üÈÝÒ×Éè¼Æ£¬¸ü¿É¶Á£¬¸ü¿É¿¿¡£
5270
5271 \section{Logging ÈÕÖ¾ \label{logging}}
5272
5273 The \ulink{\module{logging}}{../lib/module-logging.html} module offers
5274 a full featured and flexible logging system. At its simplest, log
5275 messages are sent to a file or to \code{sys.stderr}:
5276
5277 \ulink{\module{logging}}{../lib/module-logging.html} Ä£¿éÌṩÁËÍêÕûºÍÁé»îµÄÈÕ־ϵͳ¡£Ëü×î¼òµ¥µÄÓ÷¨ÊǼǼÐÅÏ¢²¢·¢Ë͵½Ò»¸öÎļþ»ò \code{sys.stderr}:
5278
5279 \begin{verbatim}
5280 import logging
5281 logging.debug('Debugging information')
5282 logging.info('Informational message')
5283 logging.warning('Warning:config file %s not found', 'server.conf')
5284 logging.error('Error occurred')
5285 logging.critical('Critical error -- shutting down')
5286 \end{verbatim}
5287
5288 This produces the following output:
5289 ÕâÀïÊÇÊä³ö£º
5290
5291 \begin{verbatim}
5292 WARNING:root:Warning:config file server.conf not found
5293 ERROR:root:Error occurred
5294 CRITICAL:root:Critical error -- shutting down
5295 \end{verbatim}
5296
5297 By default, informational and debugging messages are suppressed and the
5298 output is sent to standard error. Other output options include routing
5299 messages through email, datagrams, sockets, or to an HTTP Server. New
5300 filters can select different routing based on message priority:
5301 \constant{DEBUG}, \constant{INFO}, \constant{WARNING}, \constant{ERROR},
5302 and \constant{CRITICAL}.
5303
5304 ĬÈÏÇé¿öϲ¶»ñÐÅÏ¢ºÍµ÷ÊÔÏûÏ¢²¢½«Êä³ö·¢Ë͵½±ê×¼´íÎóÁ÷¡£ÆäËü¿ÉÑ¡µÄ·ÓÉÐÅÏ¢·½Ê½Í¨¹ýemail£¬Êý¾Ý±¨ÎÄ£¬socket»òÕßHTTP Server¡£»ùÓÚÏûÏ¢ÊôÐÔ£¬ÐµĹýÂËÆ÷¿ÉÒÔÑ¡Ôñ²»Í¬µÄ·ÓÉ£º\constant{DEBUG},\constant{INFO}£¬\constant{WARNING}£¬\constant{ERROR} ºÍ \constant{CRITICAL}¡£
5305
5306 The logging system can be configured directly from Python or can be
5307 loaded from a user editable configuration file for customized logging
5308 without altering the application.
5309
5310 ÈÕ־ϵͳ¿ÉÒÔÖ±½ÓÔÚ Python Öж¨ÖÆ£¬Ò²¿ÉÒÔ²»¾¹ýÓ¦ÓóÌÐòÖ±½ÓÔÚÒ»¸öÓû§¿É±à¼µÄÅäÖÃÎļþÖмÓÔØ¡£
5311
5312 \section{Weak References ÈõÒýÓÃ\label{weak-references}}
5313
5314 Python does automatic memory management (reference counting for most
5315 objects and garbage collection to eliminate cycles). The memory is
5316 freed shortly after the last reference to it has been eliminated.
5317
5318 Python ×Ô¶¯½øÐÐÄÚ´æ¹ÜÀí£¨¶Ô´ó¶àÊýµÄ¶ÔÏó½øÐÐÒýÓüÆÊýºÍÀ¬»ø»ØÊÕÒÔÑ»·ÀûÓã©ÔÚ×îºóÒ»¸öÒýÓÃÏûʧºó£¬ÄÚ´æ»áºÜ¿ìÊÍ·Å¡£
5319
5320 This approach works fine for most applications but occasionally there
5321 is a need to track objects only as long as they are being used by
5322 something else. Unfortunately, just tracking them creates a reference
5323 that makes them permanent. The
5324 \ulink{\module{weakref}}{../lib/module-weakref.html} module provides
5325 tools for tracking objects without creating a reference. When the
5326 object is no longer needed, it is automatically removed from a weakref
5327 table and a callback is triggered for weakref objects. Typical
5328 applications include caching objects that are expensive to create:
5329
5330 Õâ¸ö¹¤×÷·½Ê½¶Ô´ó¶àÊýÓ¦ÓóÌÐò¹¤×÷Á¼ºÃ£¬µ«ÊÇż¶û»áÐèÒª¸ú×Ù¶ÔÏóÀ´×öһЩÊ¡£²»ÐÒµÄÊÇ£¬½ö½öΪ¸ú×ÙËüÃÇ´´½¨ÒýÓÃÒ²»áʹÆä³¤ÆÚ´æÔÚ¡£ \ulink{\module{weakref}}{../lib/module-weakref.html} Ä£¿éÌṩÁ˲»Óô´½¨ÒýÓõĸú×Ù¶ÔÏ󹤾ߣ¬Ò»µ©¶ÔÏó²»ÔÙ´æÔÚ£¬Ëü×Ô¶¯´ÓÈõÒýÓñíÉÏɾ³ý²¢´¥·¢»Øµ÷¡£µäÐ͵ÄÓ¦ÓðüÀ¨²¶»ñÄÑÒÔ¹¹ÔìµÄ¶ÔÏó£º
5331
5332 \begin{verbatim}
5333 >>> import weakref, gc
5334 >>> class A:
5335 ... def __init__(self, value):
5336 ... self.value = value
5337 ... def __repr__(self):
5338 ... return str(self.value)
5339 ...
5340 >>> a = A(10) # create a reference
5341 >>> d = weakref.WeakValueDictionary()
5342 >>> d['primary'] = a # does not create a reference
5343 >>> d['primary'] # fetch the object if it is still alive
5344 10
5345 >>> del a # remove the one reference
5346 >>> gc.collect() # run garbage collection right away
5347 0
5348 >>> d['primary'] # entry was automatically removed
5349 Traceback (most recent call last):
5350 File "<pyshell#108>", line 1, in -toplevel-
5351 d['primary'] # entry was automatically removed
5352 File "C:/PY24/lib/weakref.py", line 46, in __getitem__
5353 o = self.data[key]()
5354 KeyError: 'primary'
5355 \end{verbatim}
5356
5357 \section{Tools for Working with Lists Á´±í¹¤¾ß \label{list-tools}}
5358
5359 Many data structure needs can be met with the built-in list type.
5360 However, sometimes there is a need for alternative implementations
5361 with different performance trade-offs.
5362
5363 ºÜ¶àÊý¾Ý½á¹¹¿ÉÄÜ»áÓõ½ÄÚÖÃÁ´±íÀàÐÍ¡£È»¶ø£¬ÓÐʱ¿ÉÄÜÐèÒª²»Í¬ÐÔÄÜ´ú¼ÛµÄʵÏÖ¡£
5364
5365 The \ulink{\module{array}}{../lib/module-array.html} module provides an
5366 \class{array()} object that is like a list that stores only homogenous
5367 data and stores it more compactly. The following example shows an array
5368 of numbers stored as two byte unsigned binary numbers (typecode
5369 \code{"H"}) rather than the usual 16 bytes per entry for regular lists
5370 of python int objects:
5371
5372 \ulink{\module{array}}{../lib/module-array.html}Ä£¿éÌṩÁËÒ»¸öÀàËÆÁ´±íµÄ \class{array()} ¶ÔÏó£¬Ëü½ö½öÊÇ´æ´¢Êý¾Ý£¬¸üΪ½ô´Õ¡£ÒÔϵÄʾÀýÑÝʾÁËÒ»¸ö´æ´¢Ë«×Ö½ÚÎÞ·ûºÅÕûÊýµÄÊý×飨ÀàÐͱàÂë \code{"H"}£©¶ø·Ç´æ´¢16×Ö½Ú Python ÕûÊý¶ÔÏóµÄÆÕͨÕý¹æÁ´±í£¬£º
5373
5374 \begin{verbatim}
5375 >>> from array import array
5376 >>> a = array('H', [4000, 10, 700, 22222])
5377 >>> sum(a)
5378 26932
5379 >>> a[1:3]
5380 array('H', [10, 700])
5381 \end{verbatim}
5382
5383 The \ulink{\module{collections}}{../lib/module-collections.html} module
5384 provides a \class{deque()} object that is like a list with faster
5385 appends and pops from the left side but slower lookups in the middle.
5386 These objects are well suited for implementing queues and breadth first
5387 tree searches:
5388
5389 \ulink{\module{collections}}{../lib/module-collections.html} Ä£¿éÌṩÁËÀàËÆÁ´±íµÄ \class{deque()} ¶ÔÏó£¬Ëü´Ó×ó±ßÌí¼Ó£¨append£©ºÍµ¯³ö£¨pop£©¸ü¿ì£¬µ«ÊÇÔÚÄÚ²¿²éѯ¸üÂý¡£ÕâЩ¶ÔÏó¸üÊÊÓÃÓÚ¶ÓÁÐʵÏֺ͹ã¶ÈÓÅÏȵÄÊ÷ËÑË÷£º
5390
5391 \begin{verbatim}
5392 >>> from collections import deque
5393 >>> d = deque(["task1", "task2", "task3"])
5394 >>> d.append("task4")
5395 >>> print "Handling", d.popleft()
5396 Handling task1
5397
5398 unsearched = deque([starting_node])
5399 def breadth_first_search(unsearched):
5400 node = unsearched.popleft()
5401 for m in gen_moves(node):
5402 if is_goal(m):
5403 return m
5404 unsearched.append(m)
5405 \end{verbatim}
5406
5407 In addition to alternative list implementations, the library also offers
5408 other tools such as the \ulink{\module{bisect}}{../lib/module-bisect.html}
5409 module with functions for manipulating sorted lists:
5410
5411 ³ýÁËÁ´±íµÄÌæ´úʵÏÖ£¬¸Ã¿â»¹ÌṩÁË \ulink{\module{bisect}}{../lib/module-bisect.html} ÕâÑùµÄÄ£¿éÒÔ²Ù×÷´æ´¢Á´±í£º
5412
5413 \begin{verbatim}
5414 >>> import bisect
5415 >>> scores = [(100, 'perl'), (200, 'tcl'), (400, 'lua'), (500, 'python')]
5416 >>> bisect.insort(scores, (300, 'ruby'))
5417 >>> scores
5418 [(100, 'perl'), (200, 'tcl'), (300, 'ruby'), (400, 'lua'), (500, 'python')]
5419 \end{verbatim}
5420
5421 The \ulink{\module{heapq}}{../lib/module-heapq.html} module provides
5422 functions for implementing heaps based on regular lists. The lowest
5423 valued entry is always kept at position zero. This is useful for
5424 applications which repeatedly access the smallest element but do not
5425 want to run a full list sort:
5426
5427 \ulink{\module{heapq}}{../lib/module-heapq.html} ÌṩÁË»ùÓÚÕý¹æÁ´±íµÄ¶ÑʵÏÖ¡£×îСµÄÖµ×ÜÊDZ£³ÖÔÚ0µã¡£ÕâÔÚÏ£ÍûÑ»··ÃÎÊ×îÐ¡ÔªËØµ«ÊDz»ÏëÖ´ÐÐÍêÕû¶ÑÅÅÐòµÄʱºò·Ç³£ÓÐÓá£
5428
5429 \begin{verbatim}
5430 >>> from heapq import heapify, heappop, heappush
5431 >>> data = [1, 3, 5, 7, 9, 2, 4, 6, 8, 0]
5432 >>> heapify(data) # rearrange the list into heap order
5433 >>> heappush(data, -5) # add a new entry
5434 >>> [heappop(data) for i in range(3)] # fetch the three smallest entries
5435 [-5, 0, 1]
5436 \end{verbatim}
5437
5438
5439 \section{Decimal Floating Point Arithmetic Ê®½øÖƸ¡µãÊýËã·¨ \label{decimal-fp}}
5440
5441 The \ulink{\module{decimal}}{../lib/module-decimal.html} module offers a
5442 \class{Decimal} datatype for decimal floating point arithmetic. Compared to
5443 the built-in \class{float} implementation of binary floating point, the new
5444 class is especially helpful for financial applications and other uses which
5445 require exact decimal representation, control over precision, control over
5446 rounding to meet legal or regulatory requirements, tracking of significant
5447 decimal places, or for applications where the user expects the results to
5448 match calculations done by hand.
5449
5450 \ulink{\module{decimal}}{../lib/module-decimal.html} Ä£¿éÌṩÁËÒ»¸ö \class{Decimal} Êý¾ÝÀàÐÍÓÃÓÚ¸¡µãÊý¼ÆËã¡£Ïà±ÈÄÚÖõĶþ½øÖƸ¡µãÊýʵÏÖ \class{float}£¬ÐÂÀàÐÍÌØ±ðÊÊÓÃÓÚ½ðÈÚÓ¦ÓÃºÍÆäËüÐèÒª¾«È·Ê®½øÖƱí´ïµÄ³¡ºÏ£¬¿ØÖƾ«¶È£¬¿ØÖÆÉáÈëÒÔÊÊÓ¦·¨ÂÉ»òÕ߹涨ҪÇó£¬È·±£Ê®½øÖÆÊýλ¾«¶È£¬»òÕßÓû§Ï£ÍûÓÃ×÷Êýѧ¼ÆËãµÄ³¡ºÏ¡£
5451
5452 For example, calculating a 5\%{} tax on a 70 cent phone charge gives
5453 different results in decimal floating point and binary floating point.
5454 The difference becomes significant if the results are rounded to the
5455 nearest cent:
5456
5457 ÀýÈ磬¼ÆËã 70 ·Öµç»°·ÑµÄ 5\%{} ˰¼ÆË㣬ʮ½øÖƸ¡µãÊýºÍ¶þ½øÖƸ¡µãÊý¼ÆËã½á¹ûµÄ²î±ðÈçÏ¡£Èç¹ûÔÚ·ÖÖµÉÏÉáÈ룬Õâ¸ö²î±ð¾ÍºÜÖØÒªÁË¡£
5458
5459 \begin{verbatim}
5460 >>> from decimal import *
5461 >>> Decimal('0.70') * Decimal('1.05')
5462 Decimal("0.7350")
5463 >>> .70 * 1.05
5464 0.73499999999999999
5465 \end{verbatim}
5466
5467 The \class{Decimal} result keeps a trailing zero, automatically inferring four
5468 place significance from multiplicands with two place significance. Decimal reproduces
5469 mathematics as done by hand and avoids issues that can arise when binary
5470 floating point cannot exactly represent decimal quantities.
5471
5472 \class{Decimal} µÄ½á¹û×ÜÊDZ£ÓнáβµÄ0£¬×Ô¶¯´ÓÁ½Î»¾«¶ÈÑÓÉìµ½4λ¡£DecimalÖØÏÖÁËÊÖ¹¤µÄÊýѧÔËË㣬Õâ¾ÍÈ·±£Á˶þ½øÖƸ¡µãÊýÎÞ·¨¾«È·±£ÓеÄÊý¾Ý¾«¶È¡£
5473
5474 Exact representation enables the \class{Decimal} class to perform
5475 modulo calculations and equality tests that are unsuitable for binary
5476 floating point:
5477
5478 ¸ß¾«¶Èʹ \class{Decimal} ¿ÉÒÔÖ´Ðжþ½øÖƸ¡µãÊýÎÞ·¨½øÐеÄÄ£ÔËËãºÍµÈÖµ²âÊÔ¡£
5479
5480 \begin{verbatim}
5481 >>> Decimal('1.00') % Decimal('.10')
5482 Decimal("0.00")
5483 >>> 1.00 % 0.10
5484 0.09999999999999995
5485
5486 >>> sum([Decimal('0.1')]*10) == Decimal('1.0')
5487 True
5488 >>> sum([0.1]*10) == 1.0
5489 False
5490 \end{verbatim}
5491
5492 The \module{decimal} module provides arithmetic with as much precision as
5493 needed:
5494
5495 \module{decimal} ÌṩÁ˾«¶ÈËã·¨¡£
5496
5497 \begin{verbatim}
5498 >>> getcontext().prec = 36
5499 >>> Decimal(1) / Decimal(7)
5500 Decimal("0.142857142857142857142857142857142857")
5501 \end{verbatim}
5502
5503
5504
5505 \chapter{What Now? \label{whatNow}}
5506
5507 Reading this tutorial has probably reinforced your interest in using
5508 Python --- you should be eager to apply Python to solving your
5509 real-world problems. Where should you go to learn more?
5510
5511 This tutorial is part of Python's documentation set.
5512 Some other documents in the set are:
5513
5514 \begin{itemize}
5515
5516 \item \citetitle[../lib/lib.html]{Python Library Reference}:
5517
5518 You should browse through this manual, which gives complete (though
5519 terse) reference material about types, functions, and the modules in
5520 the standard library. The standard Python distribution includes a
5521 \emph{lot} of additional code. There are modules to read \UNIX{}
5522 mailboxes, retrieve documents via HTTP, generate random numbers, parse
5523 command-line options, write CGI programs, compress data, and many other tasks.
5524 Skimming through the Library Reference will give you an idea of
5525 what's available.
5526
5527 \item \citetitle[../inst/inst.html]{Installing Python Modules}
5528 explains how to install external modules written by other Python
5529 users.
5530
5531 \item \citetitle[../ref/ref.html]{Language Reference}: A detailed
5532 explanation of Python's syntax and semantics. It's heavy reading,
5533 but is useful as a complete guide to the language itself.
5534
5535 \end{itemize}
5536
5537 More Python resources:
5538
5539 \begin{itemize}
5540
5541 \item \url{http://www.python.org}: The major Python Web site. It contains
5542 code, documentation, and pointers to Python-related pages around the
5543 Web. This Web site is mirrored in various places around the
5544 world, such as Europe, Japan, and Australia; a mirror may be faster
5545 than the main site, depending on your geographical location.
5546
5547 \item \url{http://docs.python.org}: Fast access to Python's
5548 documentation.
5549
5550 \item \url{http://cheeseshop.python.org}:
5551 The Python Package Index, nicknamed the Cheese Shop,
5552 is an index of user-created Python modules that are available for
5553 download. Once you begin releasing code, you can register it
5554 here so that others can find it.
5555
5556 \item \url{http://aspn.activestate.com/ASPN/Python/Cookbook/}: The
5557 Python Cookbook is a sizable collection of code examples, larger
5558 modules, and useful scripts. Particularly notable contributions are
5559 collected in a book also titled \citetitle{Python Cookbook} (O'Reilly
5560 \& Associates, ISBN 0-596-00797-3.)
5561
5562 \end{itemize}
5563
5564
5565 For Python-related questions and problem reports, you can post to the
5566 newsgroup \newsgroup{comp.lang.python}, or send them to the mailing
5567 list at \email{[email protected]}. The newsgroup and mailing list
5568 are gatewayed, so messages posted to one will automatically be
5569 forwarded to the other. There are around 120 postings a day (with peaks
5570 up to several hundred),
5571 % Postings figure based on average of last six months activity as
5572 % reported by www.egroups.com; Jan. 2000 - June 2000: 21272 msgs / 182
5573 % days = 116.9 msgs / day and steadily increasing.
5574 asking (and answering) questions, suggesting new features, and
5575 announcing new modules. Before posting, be sure to check the list of
5576 \ulink{Frequently Asked Questions}{http://www.python.org/doc/faq/} (also called the FAQ), or look for it in the
5577 \file{Misc/} directory of the Python source distribution. Mailing
5578 list archives are available at \url{http://mail.python.org/pipermail/}.
5579 The FAQ answers many of the questions that come up again and again,
5580 and may already contain the solution for your problem.
5581
5582
5583 \appendix
5584
5585 \chapter{Interactive Input Editing and History Substitution\label{interacting}}
5586
5587 Some versions of the Python interpreter support editing of the current
5588 input line and history substitution, similar to facilities found in
5589 the Korn shell and the GNU Bash shell. This is implemented using the
5590 \emph{GNU Readline} library, which supports Emacs-style and vi-style
5591 editing. This library has its own documentation which I won't
5592 duplicate here; however, the basics are easily explained. The
5593 interactive editing and history described here are optionally
5594 available in the \UNIX{} and Cygwin versions of the interpreter.
5595
5596 This chapter does \emph{not} document the editing facilities of Mark
5597 Hammond's PythonWin package or the Tk-based environment, IDLE,
5598 distributed with Python. The command line history recall which
5599 operates within DOS boxes on NT and some other DOS and Windows flavors
5600 is yet another beast.
5601
5602 \section{Line Editing \label{lineEditing}}
5603
5604 If supported, input line editing is active whenever the interpreter
5605 prints a primary or secondary prompt. The current line can be edited
5606 using the conventional Emacs control characters. The most important
5607 of these are: \kbd{C-A} (Control-A) moves the cursor to the beginning
5608 of the line, \kbd{C-E} to the end, \kbd{C-B} moves it one position to
5609 the left, \kbd{C-F} to the right. Backspace erases the character to
5610 the left of the cursor, \kbd{C-D} the character to its right.
5611 \kbd{C-K} kills (erases) the rest of the line to the right of the
5612 cursor, \kbd{C-Y} yanks back the last killed string.
5613 \kbd{C-underscore} undoes the last change you made; it can be repeated
5614 for cumulative effect.
5615
5616 \section{History Substitution \label{history}}
5617
5618 History substitution works as follows. All non-empty input lines
5619 issued are saved in a history buffer, and when a new prompt is given
5620 you are positioned on a new line at the bottom of this buffer.
5621 \kbd{C-P} moves one line up (back) in the history buffer,
5622 \kbd{C-N} moves one down. Any line in the history buffer can be
5623 edited; an asterisk appears in front of the prompt to mark a line as
5624 modified. Pressing the \kbd{Return} key passes the current line to
5625 the interpreter. \kbd{C-R} starts an incremental reverse search;
5626 \kbd{C-S} starts a forward search.
5627
5628 \section{Key Bindings \label{keyBindings}}
5629
5630 The key bindings and some other parameters of the Readline library can
5631 be customized by placing commands in an initialization file called
5632 \file{\~{}/.inputrc}. Key bindings have the form
5633
5634 \begin{verbatim}
5635 key-name: function-name
5636 \end{verbatim}
5637
5638 or
5639
5640 \begin{verbatim}
5641 "string": function-name
5642 \end{verbatim}
5643
5644 and options can be set with
5645
5646 \begin{verbatim}
5647 set option-name value
5648 \end{verbatim}
5649
5650 For example:
5651
5652 \begin{verbatim}
5653 # I prefer vi-style editing:
5654 set editing-mode vi
5655
5656 # Edit using a single line:
5657 set horizontal-scroll-mode On
5658
5659 # Rebind some keys:
5660 Meta-h: backward-kill-word
5661 "\C-u": universal-argument
5662 "\C-x\C-r": re-read-init-file
5663 \end{verbatim}
5664
5665 Note that the default binding for \kbd{Tab} in Python is to insert a
5666 \kbd{Tab} character instead of Readline's default filename completion
5667 function. If you insist, you can override this by putting
5668
5669 \begin{verbatim}
5670 Tab: complete
5671 \end{verbatim}
5672
5673 in your \file{\~{}/.inputrc}. (Of course, this makes it harder to
5674 type indented continuation lines if you're accustomed to using
5675 \kbd{Tab} for that purpose.)
5676
5677 Automatic completion of variable and module names is optionally
5678 available. To enable it in the interpreter's interactive mode, add
5679 the following to your startup file:\footnote{
5680 Python will execute the contents of a file identified by the
5681 \envvar{PYTHONSTARTUP} environment variable when you start an
5682 interactive interpreter.}
5683 \refstmodindex{rlcompleter}\refbimodindex{readline}
5684
5685 \begin{verbatim}
5686 import rlcompleter, readline
5687 readline.parse_and_bind('tab: complete')
5688 \end{verbatim}
5689
5690 This binds the \kbd{Tab} key to the completion function, so hitting
5691 the \kbd{Tab} key twice suggests completions; it looks at Python
5692 statement names, the current local variables, and the available module
5693 names. For dotted expressions such as \code{string.a}, it will
5694 evaluate the expression up to the final \character{.} and then
5695 suggest completions from the attributes of the resulting object. Note
5696 that this may execute application-defined code if an object with a
5697 \method{__getattr__()} method is part of the expression.
5698
5699 A more capable startup file might look like this example. Note that
5700 this deletes the names it creates once they are no longer needed; this
5701 is done since the startup file is executed in the same namespace as
5702 the interactive commands, and removing the names avoids creating side
5703 effects in the interactive environment. You may find it convenient
5704 to keep some of the imported modules, such as
5705 \ulink{\module{os}}{../lib/module-os.html}, which turn
5706 out to be needed in most sessions with the interpreter.
5707
5708 \begin{verbatim}
5709 # Add auto-completion and a stored history file of commands to your Python
5710 # interactive interpreter. Requires Python 2.0+, readline. Autocomplete is
5711 # bound to the Esc key by default (you can change it - see readline docs).
5712 #
5713 # Store the file in ~/.pystartup, and set an environment variable to point
5714 # to it: "export PYTHONSTARTUP=/max/home/itamar/.pystartup" in bash.
5715 #
5716 # Note that PYTHONSTARTUP does *not* expand "~", so you have to put in the
5717 # full path to your home directory.
5718
5719 import atexit
5720 import os
5721 import readline
5722 import rlcompleter
5723
5724 historyPath = os.path.expanduser("~/.pyhistory")
5725
5726 def save_history(historyPath=historyPath):
5727 import readline
5728 readline.write_history_file(historyPath)
5729
5730 if os.path.exists(historyPath):
5731 readline.read_history_file(historyPath)
5732
5733 atexit.register(save_history)
5734 del os, atexit, readline, rlcompleter, save_history, historyPath
5735 \end{verbatim}
5736
5737
5738 \section{Commentary \label{commentary}}
5739
5740 This facility is an enormous step forward compared to earlier versions
5741 of the interpreter; however, some wishes are left: It would be nice if
5742 the proper indentation were suggested on continuation lines (the
5743 parser knows if an indent token is required next). The completion
5744 mechanism might use the interpreter's symbol table. A command to
5745 check (or even suggest) matching parentheses, quotes, etc., would also
5746 be useful.
5747
5748
5749 \chapter{Floating Point Arithmetic: Issues and Limitations\label{fp-issues}}
5750 \sectionauthor{Tim Peters}{tim_[email protected]}
5751
5752 Floating-point numbers are represented in computer hardware as
5753 base 2 (binary) fractions. For example, the decimal fraction
5754
5755 \begin{verbatim}
5756 0.125
5757 \end{verbatim}
5758
5759 has value 1/10 + 2/100 + 5/1000, and in the same way the binary fraction
5760
5761 \begin{verbatim}
5762 0.001
5763 \end{verbatim}
5764
5765 has value 0/2 + 0/4 + 1/8. These two fractions have identical values,
5766 the only real difference being that the first is written in base 10
5767 fractional notation, and the second in base 2.
5768
5769 Unfortunately, most decimal fractions cannot be represented exactly as
5770 binary fractions. A consequence is that, in general, the decimal
5771 floating-point numbers you enter are only approximated by the binary
5772 floating-point numbers actually stored in the machine.
5773
5774 The problem is easier to understand at first in base 10. Consider the
5775 fraction 1/3. You can approximate that as a base 10 fraction:
5776
5777 \begin{verbatim}
5778 0.3
5779 \end{verbatim}
5780
5781 or, better,
5782
5783 \begin{verbatim}
5784 0.33
5785 \end{verbatim}
5786
5787 or, better,
5788
5789 \begin{verbatim}
5790 0.333
5791 \end{verbatim}
5792
5793 and so on. No matter how many digits you're willing to write down, the
5794 result will never be exactly 1/3, but will be an increasingly better
5795 approximation of 1/3.
5796
5797 In the same way, no matter how many base 2 digits you're willing to
5798 use, the decimal value 0.1 cannot be represented exactly as a base 2
5799 fraction. In base 2, 1/10 is the infinitely repeating fraction
5800
5801 \begin{verbatim}
5802 0.0001100110011001100110011001100110011001100110011...
5803 \end{verbatim}
5804
5805 Stop at any finite number of bits, and you get an approximation. This
5806 is why you see things like:
5807
5808 \begin{verbatim}
5809 >>> 0.1
5810 0.10000000000000001
5811 \end{verbatim}
5812
5813 On most machines today, that is what you'll see if you enter 0.1 at
5814 a Python prompt. You may not, though, because the number of bits
5815 used by the hardware to store floating-point values can vary across
5816 machines, and Python only prints a decimal approximation to the true
5817 decimal value of the binary approximation stored by the machine. On
5818 most machines, if Python were to print the true decimal value of
5819 the binary approximation stored for 0.1, it would have to display
5820
5821 \begin{verbatim}
5822 >>> 0.1
5823 0.1000000000000000055511151231257827021181583404541015625
5824 \end{verbatim}
5825
5826 instead! The Python prompt uses the builtin
5827 \function{repr()} function to obtain a string version of everything it
5828 displays. For floats, \code{repr(\var{float})} rounds the true
5829 decimal value to 17 significant digits, giving
5830
5831 \begin{verbatim}
5832 0.10000000000000001
5833 \end{verbatim}
5834
5835 \code{repr(\var{float})} produces 17 significant digits because it
5836 turns out that's enough (on most machines) so that
5837 \code{eval(repr(\var{x})) == \var{x}} exactly for all finite floats
5838 \var{x}, but rounding to 16 digits is not enough to make that true.
5839
5840 Note that this is in the very nature of binary floating-point: this is
5841 not a bug in Python, and it is not a bug in your code either. You'll
5842 see the same kind of thing in all languages that support your
5843 hardware's floating-point arithmetic (although some languages may
5844 not \emph{display} the difference by default, or in all output modes).
5845
5846 Python's builtin \function{str()} function produces only 12
5847 significant digits, and you may wish to use that instead. It's
5848 unusual for \code{eval(str(\var{x}))} to reproduce \var{x}, but the
5849 output may be more pleasant to look at:
5850
5851 \begin{verbatim}
5852 >>> print str(0.1)
5853 0.1
5854 \end{verbatim}
5855
5856 It's important to realize that this is, in a real sense, an illusion:
5857 the value in the machine is not exactly 1/10, you're simply rounding
5858 the \emph{display} of the true machine value.
5859
5860 Other surprises follow from this one. For example, after seeing
5861
5862 \begin{verbatim}
5863 >>> 0.1
5864 0.10000000000000001
5865 \end{verbatim}
5866
5867 you may be tempted to use the \function{round()} function to chop it
5868 back to the single digit you expect. But that makes no difference:
5869
5870 \begin{verbatim}
5871 >>> round(0.1, 1)
5872 0.10000000000000001
5873 \end{verbatim}
5874
5875 The problem is that the binary floating-point value stored for "0.1"
5876 was already the best possible binary approximation to 1/10, so trying
5877 to round it again can't make it better: it was already as good as it
5878 gets.
5879
5880 Another consequence is that since 0.1 is not exactly 1/10,
5881 summing ten values of 0.1 may not yield exactly 1.0, either:
5882
5883 \begin{verbatim}
5884 >>> sum = 0.0
5885 >>> for i in range(10):
5886 ... sum += 0.1
5887 ...
5888 >>> sum
5889 0.99999999999999989
5890 \end{verbatim}
5891
5892 Binary floating-point arithmetic holds many surprises like this. The
5893 problem with "0.1" is explained in precise detail below, in the
5894 "Representation Error" section. See
5895 \citetitle[http://www.lahey.com/float.htm]{The Perils of Floating
5896 Point} for a more complete account of other common surprises.
5897
5898 As that says near the end, ``there are no easy answers.'' Still,
5899 don't be unduly wary of floating-point! The errors in Python float
5900 operations are inherited from the floating-point hardware, and on most
5901 machines are on the order of no more than 1 part in 2**53 per
5902 operation. That's more than adequate for most tasks, but you do need
5903 to keep in mind that it's not decimal arithmetic, and that every float
5904 operation can suffer a new rounding error.
5905
5906 While pathological cases do exist, for most casual use of
5907 floating-point arithmetic you'll see the result you expect in the end
5908 if you simply round the display of your final results to the number of
5909 decimal digits you expect. \function{str()} usually suffices, and for
5910 finer control see the discussion of Python's \code{\%} format
5911 operator: the \code{\%g}, \code{\%f} and \code{\%e} format codes
5912 supply flexible and easy ways to round float results for display.
5913
5914
5915 \section{Representation Error
5916 \label{fp-error}}
5917
5918 This section explains the ``0.1'' example in detail, and shows how
5919 you can perform an exact analysis of cases like this yourself. Basic
5920 familiarity with binary floating-point representation is assumed.
5921
5922 \dfn{Representation error} refers to the fact that some (most, actually)
5923 decimal fractions cannot be represented exactly as binary (base 2)
5924 fractions. This is the chief reason why Python (or Perl, C, \Cpp,
5925 Java, Fortran, and many others) often won't display the exact decimal
5926 number you expect:
5927
5928 \begin{verbatim}
5929 >>> 0.1
5930 0.10000000000000001
5931 \end{verbatim}
5932
5933 Why is that? 1/10 is not exactly representable as a binary fraction.
5934 Almost all machines today (November 2000) use IEEE-754 floating point
5935 arithmetic, and almost all platforms map Python floats to IEEE-754
5936 "double precision". 754 doubles contain 53 bits of precision, so on
5937 input the computer strives to convert 0.1 to the closest fraction it can
5938 of the form \var{J}/2**\var{N} where \var{J} is an integer containing
5939 exactly 53 bits. Rewriting
5940
5941 \begin{verbatim}
5942 1 / 10 ~= J / (2**N)
5943 \end{verbatim}
5944
5945 as
5946
5947 \begin{verbatim}
5948 J ~= 2**N / 10
5949 \end{verbatim}
5950
5951 and recalling that \var{J} has exactly 53 bits (is \code{>= 2**52} but
5952 \code{< 2**53}), the best value for \var{N} is 56:
5953
5954 \begin{verbatim}
5955 >>> 2**52
5956 4503599627370496L
5957 >>> 2**53
5958 9007199254740992L
5959 >>> 2**56/10
5960 7205759403792793L
5961 \end{verbatim}
5962
5963 That is, 56 is the only value for \var{N} that leaves \var{J} with
5964 exactly 53 bits. The best possible value for \var{J} is then that
5965 quotient rounded:
5966
5967 \begin{verbatim}
5968 >>> q, r = divmod(2**56, 10)
5969 >>> r
5970 6L
5971 \end{verbatim}
5972
5973 Since the remainder is more than half of 10, the best approximation is
5974 obtained by rounding up:
5975
5976 \begin{verbatim}
5977 >>> q+1
5978 7205759403792794L
5979 \end{verbatim}
5980
5981 Therefore the best possible approximation to 1/10 in 754 double
5982 precision is that over 2**56, or
5983
5984 \begin{verbatim}
5985 7205759403792794 / 72057594037927936
5986 \end{verbatim}
5987
5988 Note that since we rounded up, this is actually a little bit larger than
5989 1/10; if we had not rounded up, the quotient would have been a little
5990 bit smaller than 1/10. But in no case can it be \emph{exactly} 1/10!
5991
5992 So the computer never ``sees'' 1/10: what it sees is the exact
5993 fraction given above, the best 754 double approximation it can get:
5994
5995 \begin{verbatim}
5996 >>> .1 * 2**56
5997 7205759403792794.0
5998 \end{verbatim}
5999
6000 If we multiply that fraction by 10**30, we can see the (truncated)
6001 value of its 30 most significant decimal digits:
6002
6003 \begin{verbatim}
6004 >>> 7205759403792794 * 10**30 / 2**56
6005 100000000000000005551115123125L
6006 \end{verbatim}
6007
6008 meaning that the exact number stored in the computer is approximately
6009 equal to the decimal value 0.100000000000000005551115123125. Rounding
6010 that to 17 significant digits gives the 0.10000000000000001 that Python
6011 displays (well, will display on any 754-conforming platform that does
6012 best-possible input and output conversions in its C library --- yours may
6013 not!).
6014
6015 \chapter{History and License}
6016 \input{license}
6017
6018 \input{glossary}
6019
6020 \input{tut.ind}
6021 \end{CJK*}
6022 \end{document}
Attached Files
To refer to attachments on a page, use attachment:filename, as shown below in the list of files. Do NOT use the URL of the [get] link, since this is subject to change and can break easily.You are not allowed to attach a file to this page.