📄 node6.html
字号:
<div class="verbatim"><pre>
parrot(1000)
parrot(action = 'VOOOOOM', voltage = 1000000)
parrot('a thousand', state = 'pushing up the daisies')
parrot('a million', 'bereft of life', 'jump')</pre></div><P>but the following calls would all be invalid:<P>不过以下几种调用是无效的:<P><div class="verbatim"><pre>
parrot() # required argument missing
parrot(voltage=5.0, 'dead') # non-keyword argument following keyword
parrot(110, voltage=220) # duplicate value for argument
parrot(actor='John Cleese') # unknown keyword</pre></div><P>In general, an argument list must have any positional arguments
followed by any keyword arguments, where the keywords must be chosen
from the formal parameter names. It's not important whether a formal
parameter has a default value or not. No argument may receive a
value more than once -- formal parameter names corresponding to
positional arguments cannot be used as keywords in the same calls.
Here's an example that fails due to this restriction:<P>通常,参数列表中的每一个关键字都必须来自于形式参数,每个参数都有对应的关键字。形式参数有没有默认值并不重要。实际参数不能一次赋多个值——形式参数不能在同一次调用中同时使用位置和关键字绑定值。这里有一个例子演示了在这种约束下所出现的失败情况:<P><div class="verbatim"><pre>
>>> def function(a):
... pass
...
>>> function(0, a=0)
Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: function() got multiple values for keyword argument 'a'</pre></div><P>When a final formal parameter of the form <code>**<var>name</var></code> is
present, it receives a <a class="ulink" href="../lib/typesmapping.html" >dictionary</a> containing all keyword arguments
whose keyword doesn't correspond to a formal parameter. This may be
combined with a formal parameter of the form
<code>*<var>name</var></code> (described in the next subsection) which receives a
tuple containing the positional arguments beyond the formal parameter
list. (<code>*<var>name</var></code> must occur before <code>**<var>name</var></code>.)
For example, if we define a function like this:<P>引入一个形如 <code>**name</code> 的参数时,它接收一个 <a class="ulink" href="../lib/typesmapping.html" >字典</a> ,该字典包含了所有未出现在形式参数列表中的关键字参数。这里可能还会组合使用一个形如 <code>*<var>name</var></code> 的形式参数,它接收一个元组(下一节中会详细介绍),包含了所有没有出现在形式参数列表中的参数值。(<code>*<var>name</var></code> 必须在 <code>**<var>name</var></code> 之前出现) 例如,我们这样定义一个函数:<P><div class="verbatim"><pre>
def cheeseshop(kind, *arguments, **keywords):
print "-- Do you have any", kind, '?'
print "-- I'm sorry, we're all out of", kind
for arg in arguments: print arg
print '-'*40
keys = keywords.keys()
keys.sort()
for kw in keys: print kw, ':', keywords[kw]</pre></div><P>It could be called like this:<P>它可以像这样调用:<P><div class="verbatim"><pre>
cheeseshop('Limburger', "It's very runny, sir.",
"It's really very, VERY runny, sir.",
client='John Cleese',
shopkeeper='Michael Palin',
sketch='Cheese Shop Sketch')</pre></div><P>and of course it would print:<P>当然它会按如下内容打印:<P><div class="verbatim"><pre>
-- Do you have any Limburger ?
-- I'm sorry, we're all out of Limburger
It's very runny, sir.
It's really very, VERY runny, sir.
----------------------------------------
client : John Cleese
shopkeeper : Michael Palin
sketch : Cheese Shop Sketch</pre></div><P>Note that the <tt class="method">sort()</tt> method of the list of keyword argument
names is called before printing the contents of the <code>keywords</code>
dictionary; if this is not done, the order in which the arguments are
printed is undefined.<P>注意<tt class="method">sort()</tt>方法在关键字字典内容打印前被调用,否则的话,打印参数时的顺序是未定义的。<P><H2><A NAME="SECTION006730000000000000000"></A><A NAME="arbitraryArgs"></A><BR>4.7.3 可变参数表 Arbitrary Argument Lists </H2><P>Finally, the least frequently used option is to specify that a
function can be called with an arbitrary number of arguments. These
arguments will be wrapped up in a tuple. Before the variable number
of arguments, zero or more normal arguments may occur.<P>最后,一个最不常用的选择是可以让函数调用可变个数的参数。这些参数被包装进一个元组。在这些可变个数的参数之前,可以有零到多个普通的参数:<P><div class="verbatim"><pre>
def fprintf(file, format, *args):
file.write(format % args)
</pre></div><P><H2><A NAME="SECTION006740000000000000000"></A><A NAME="unpacking-arguments"></A><BR>4.7.4 参数列表的分拆 Unpacking Argument Lists </H2><P>The reverse situation occurs when the arguments are already in a list
or tuple but need to be unpacked for a function call requiring separate
positional arguments. For instance, the built-in <tt class="function">range()</tt>
function expects separate <var>start</var> and <var>stop</var> arguments. If they
are not available separately, write the function call with the
<code>*</code>-operator to unpack the arguments out of a list or tuple:<P>另有一种相反的情况: 当你要传递的参数已经是一个列表但要调用的函数却接受分开一个个的参数值. 这时候你要把已有的列表拆开来. 例如内建函数 <tt class="function">range()</tt> 需要要独立的 <var>start</var>, <var>stop</var> 参数. 你可以在调用函数时加一个 <code>*</code> 操作符来自动把参数列表拆开:<P><div class="verbatim"><pre>
>>> range(3, 6) # normal call with separate arguments
[3, 4, 5]
>>> args = [3, 6]
>>> range(*args) # call with arguments unpacked from a list
[3, 4, 5]</pre></div><P><H2><A NAME="SECTION006750000000000000000"></A><A NAME="lambda"></A><BR>4.7.5 Lambda 形式 Lambda Forms </H2><P>By popular demand, a few features commonly found in functional
programming languages and Lisp have been added to Python. With the
<tt class="keyword">lambda</tt> keyword, small anonymous functions can be created.
Here's a function that returns the sum of its two arguments:
"<tt class="samp">lambda a, b: a+b</tt>". Lambda forms can be used wherever function
objects are required. They are syntactically restricted to a single
expression. Semantically, they are just syntactic sugar for a normal
function definition. Like nested function definitions, lambda forms
can reference variables from the containing scope:<P>出于实际需要,有几种通常在功能性语言和 Lisp 中出现的功能加入到了 Python 。通过 <tt class="keyword">lambda</tt> 关键字,可以创建短小的匿名函数。这里有一个函数返回它的两个参数的和:"<tt class="samp">lambda a, b: a+b</tt>"。 Lambda 形式可以用于任何需要的函数对象。出于语法限制,它们只能有一个单独的表达式。语义上讲,它们只是普通函数定义中的一个语法技巧。类似于嵌套函数定义,lambda 形式可以从包含范围内引用变量:<P><div class="verbatim"><pre>
>>> def make_incrementor(n):
... return lambda x: x + n
...
>>> f = make_incrementor(42)
>>> f(0)
42
>>> f(1)
43</pre></div><P><H2><A NAME="SECTION006760000000000000000"></A><A NAME="docstrings"></A><BR>4.7.6 文档字符串 Documentation Strings </H2><P>There are emerging conventions about the content and formatting of
documentation strings.
<a id='l2h-13' xml:id='l2h-13'></a><P>这里介绍<a id='l2h-14' xml:id='l2h-14'></a>的概念和格式。<P>The first line should always be a short, concise summary of the
object's purpose. For brevity, it should not explicitly state the
object's name or type, since these are available by other means
(except if the name happens to be a verb describing a function's
operation). This line should begin with a capital letter and end with
a period.<P>第一行应该是关于对象用途的简介。简短起见,不用明确的陈述对象名或类型,因为它们可以从别的途径了解到(除非这个名字碰巧就是描述这个函数操作的动词)。这一行应该以大写字母开头,以句号结尾。<P>If there are more lines in the documentation string, the second line
should be blank, visually separating the summary from the rest of the
description. The following lines should be one or more paragraphs
describing the object's calling conventions, its side effects, etc.<P>如果文档字符串有多行,第二行应该空出来,与接下来的详细描述明确分隔。接下来的文档应该有一或多段描述对象的调用约定、边界效应等。<P>The Python parser does not strip indentation from multi-line string
literals in Python, so tools that process documentation have to strip
indentation if desired. This is done using the following convention.
The first non-blank line <em>after</em> the first line of the string
determines the amount of indentation for the entire documentation
string. (We can't use the first line since it is generally adjacent
to the string's opening quotes so its indentation is not apparent in
the string literal.) Whitespace ``equivalent'' to this indentation is
then stripped from the start of all lines of the string. Lines that
are indented less should not occur, but if they occur all their
leading whitespace should be stripped. Equivalence of whitespace
should be tested after expansion of tabs (to 8 spaces, normally).<P>Python的解释器不会从多行的文档字符串中去除缩进,所以必要的时候应当自己清除缩进。这符合通常的习惯。第一行<em>之后</em>的第一个非空行决定了整个文档的缩进格式。(我们不用第一行是因为它通常紧靠着起始的引号,缩进格式显示的不清楚。)留白“相当于”是字符串的起始缩进。每一行都不应该有缩进,如果有缩进的话,所有的留白都应该清除掉。留白的长度应当等于扩展制表符的宽度(通常是8个空格)。<P>Here is an example of a multi-line docstring:<P>以下是一个多行文档字符串的示例:<P><div class="verbatim"><pre>
>>> def my_function():
... """Do nothing, but document it.
...
... No, really, it doesn't do anything.
... """
... pass
...
>>> print my_function.__doc__
Do nothing, but document it.
No, really, it doesn't do anything.</pre></div><P><BR><HR><H4>Footnotes</H4><DL><DT><A NAME="foot2358">... object).</A><A HREF="node6.html#tex2html3"><SUP>4.1</SUP></A></DT><DD>
Actually, <em>call by object reference</em> would be a better
description, since if a mutable object is passed, the caller
will see any changes the callee makes to it (items
inserted into a list).
</DD><DT><A NAME="foot533">...函数引用的实际参数在函数调用时引入局部符号表,因此,实参总是传值调用(这里的值总是一个对象引用,而不是该对象的值)。</A><A HREF="node6.html#tex2html4"><SUP>4.2</SUP></A></DT><DD>事实上,称之为调用对象的引用更合适。因为一个可变对象传递进来后,调用者可以看到被调用对象的任何修改(如在链表中插入一个新的子项)。</DD></DL><DIV CLASS="navigation"><div class='online-navigation'><p></p><hr /><table align="center" width="100%" cellpadding="0" cellspacing="2"><tr><td class='online-navigation'><a rel="prev" title="3. Python简介 An Informal" href="node5.html"><img src='../icons/previous.png' border='0' height='32' alt='Previous Page' width='32' /></A></td><td class='online-navigation'><a rel="parent" title="Python Tutorial" href="tut.html"><img src='../icons/up.png' border='0' height='32' alt='Up One Level' width='32' /></A></td><td class='online-navigation'><a rel="next" title="5. 数据结构 Data Structures" href="node7.html"><img src='../icons/next.png' border='0' height='32' alt='Next Page' width='32' /></A></td><td align="center" width="100%" class='online-navigation'>Python Tutorial</td><td class='online-navigation'><a rel="contents" title="Table of Contents" href="node2.html"><img src='../icons/contents.png' border='0' height='32' alt='Contents' width='32' /></A></td><td class='online-navigation'><img src='../icons/blank.png' border='0' height='32' alt='' width='32' /></td><td class='online-navigation'><img src='../icons/blank.png' border='0' height='32' alt='' width='32' /></td></tr></table><div class='online-navigation'><b class="navlabel">Previous:</b><a class="sectref" rel="prev" href="node5.html">3. Python简介 An Informal</A><b class="navlabel">Up:</b><a class="sectref" rel="parent" href="tut.html">Python Tutorial</A><b class="navlabel">Next:</b><a class="sectref" rel="next" href="node7.html">5. 数据结构 Data Structures</A></div></div><hr /></DIV><!--End of Navigation Panel--><ADDRESS>译者:刘鑫(march.liu AT gmail DOT com) 由:limodou转(limodou AT gmail DOT com)<br>See <i><a href="about.html">About this document...</a></i> for information on suggesting changes.</ADDRESS></BODY></HTML>
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -