⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 node6.html

📁 python的入门教程,讲得挺不错的,有一些实例
💻 HTML
📖 第 1 页 / 共 3 页
字号:
We can create a function that writes the Fibonacci series to an
arbitrary boundary:<P><div class="verbatim"><pre>
&gt;&gt;&gt; def fib(n):    # write Fibonacci series up to n
...     """Print a Fibonacci series up to n."""
...     a, b = 0, 1
...     while b &lt; n:
...         print b,
...         a, b = b, a+b
...
&gt;&gt;&gt; # Now call the function we just defined:
... fib(2000)
1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597</pre></div><P>The keyword <tt class="keyword">def</tt> introduces a function <em>definition</em>.  It
must be followed by the function name and the parenthesized list of
formal parameters.  The statements that form the body of the function
start at the next line, and must be indented.  The first statement of
the function body can optionally be a string literal; this string
literal is the function's <a id='l2h-9' xml:id='l2h-9'></a>documentation
string, or <i class="dfn">docstring</i>.<a id='l2h-10' xml:id='l2h-10'></a><P>关键字  <tt class="keyword">def</tt>
引入了一个函数定义。在其后必须跟有函数名和包括形式参数的圆括号。函数体语句从下一行开始,必须是缩进的。函数体的第一行可以是一个字符串值,这个字符串是该函数的
<i class="dfn">(</i>文档字符串(documentation string))<a id='l2h-11' xml:id='l2h-11'></a>,也可称作 <i class="dfn">docstring</i>
。<a id='l2h-12' xml:id='l2h-12'></a><P>There are tools which use docstrings to automatically produce online
or printed documentation, or to let the user interactively browse
through code; it's good practice to include docstrings in code that
you write, so try to make a habit of it.<P>有些文档字符串工具可以在线处理或打印文档,或让用户交互的浏览代码;在代码中加入文档字符串是一个好的作法,应该养成这个习惯。<P>The <em>execution</em> of a function introduces a new symbol table used
for the local variables of the function.  More precisely, all variable
assignments in a function store the value in the local symbol table;
whereas variable references first look in the local symbol table, then
in the global symbol table, and then in the table of built-in names.
Thus,  global variables cannot be directly assigned a value within a
function (unless named in a <tt class="keyword">global</tt> statement), although
they may be referenced.<P><em>执行</em>函数时会为局部变量引入一个新的符号表。所有的局部变量都存储在这个局部符号表中。引用参数时,会先从局部符号表中查找,然后是全局符号表,然后是内置命名表。因此,全局参数虽然可以被引用,但它们不能在函数中直接赋值(除非它们用
global 语句命名)。<P>The actual parameters (arguments) to a function call are introduced in
the local symbol table of the called function when it is called; thus,
arguments are passed using <em>call by value</em> (where the
<em>value</em> is always an object <em>reference</em>, not the value of
the object).<A NAME="tex2html3"  HREF="#foot2358"><SUP>4.1</SUP></A> When a function calls another function, a new local symbol table is
created for that call.<P>函数引用的实际参数在函数调用时引入局部符号表,因此,实参总是传值调用(这里的值总是一个对象引用,而不是该对象的值)。<A NAME="tex2html4"  HREF="#foot533"><SUP>4.2</SUP></A> 一个函数被另一个函数调用时,一个新的局部符号表在调用过程中被创建。<P>A function definition introduces the function name in the current
symbol table.  The value of the function name
has a type that is recognized by the interpreter as a user-defined
function.  This value can be assigned to another name which can then
also be used as a function.  This serves as a general renaming
mechanism:<P>函数定义在当前符号表中引入函数名。作为用户定义函数,函数名有一个为解释器认可的类型值。这个值可以赋给其它命名,使其能够作为一个函数来使用。这就像一个重命名机制:<P><div class="verbatim"><pre>
&gt;&gt;&gt; fib
&lt;function fib at 10042ed0&gt;
&gt;&gt;&gt; f = fib
&gt;&gt;&gt; f(100)
1 1 2 3 5 8 13 21 34 55 89</pre></div><P>You might object that <code>fib</code> is not a function but a procedure.  In
Python, like in C, procedures are just functions that don't return a
value.  In fact, technically speaking, procedures do return a value,
albeit a rather boring one.  This value is called <code>None</code> (it's a
built-in name).  Writing the value <code>None</code> is normally suppressed by
the interpreter if it would be the only value written.  You can see it
if you really want to:<P>你可能认为<code>fib</code>不是一个函数( function ),而是一个过程( procedure )。Python 和 C 一样,过程只是一个没有返回值的函数。实际上,从技术上讲,过程也有一个返回值,虽然是一个不讨人喜欢的。这个值被称为 <code>None</code> (这是一个内置命名)。如果一个值只是 None 的话,通常解释器不会写一个 None 出来,如果你真想要查看它的话,可以这样做:<P><div class="verbatim"><pre>
&gt;&gt;&gt; print fib(0)
None</pre></div><P>It is simple to write a function that returns a list of the numbers of
the Fibonacci series, instead of printing it:<P>以下示例演示了如何从函数中返回一个包含菲波那契数列的数值链表,而不是打印它:<P><div class="verbatim"><pre>
&gt;&gt;&gt; def fib2(n): # return Fibonacci series up to n
...     """Return a list containing the Fibonacci series up to n."""
...     result = []
...     a, b = 0, 1
...     while b &lt; n:
...         result.append(b)    # see below
...         a, b = b, a+b
...     return result
...
&gt;&gt;&gt; f100 = fib2(100)    # call it
&gt;&gt;&gt; f100                # write the result
[1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]</pre></div><P>This example, as usual, demonstrates some new Python features:<P>和以前一样,这个例子演示了一些新的 Python 功能:<P><UL><LI>The <tt class="keyword">return</tt> statement returns with a value from a function.
<tt class="keyword">return</tt> without an expression argument returns <code>None</code>.
Falling off the end of a procedure also returns <code>None</code>.<P><tt class="keyword">return</tt> 语句从函数中返回一个值,不带表达式的 <tt class="keyword">return</tt> 返回 <code>None</code>。过程结束后也会返回 <code>None</code> 。<P></LI><LI>The statement <code>result.append(b)</code> calls a <em>method</em> of the list
object <code>result</code>.  A method is a function that `belongs' to an
object and is named <code>obj.methodname</code>, where <code>obj</code> is some
object (this may be an expression), and <code>methodname</code> is the name
of a method that is defined by the object's type.  Different types
define different methods.  Methods of different types may have the
same name without causing ambiguity.  (It is possible to define your
own object types and methods, using <em>classes</em>, as discussed later
in this tutorial.)
The method <tt class="method">append()</tt> shown in the example, is defined for
list objects; it adds a new element at the end of the list.  In this
example it is equivalent to "<tt class="samp">result = result + [b]</tt>", but more
efficient.<P>语句 <code>result.append(b)</code> 称为链表对象 <code>result</code> 的一个<em>方法( method )</em>。方法是一个“属于”某个对象的函数,它被命名为 <code>obj.methodename</code> ,这里的 <code>obj</code> 是某个对象(可能是一个表达式),<code>methodename</code> 是某个在该对象类型定义中的方法的命名。不同的类型定义不同的方法。不同类型可能有同样名字的方法,但不会混淆。(当你定义自己的对象类型和方法时,可能会出现这种情况,本指南后面的章节会介绍如何使用<em>类型</em>)。示例中演示的 <tt class="method">append()</tt>方法由链表对象定义,它向链表中加入一个新元素。在示例中它等同于"<tt class="samp">"result = result + [b]"</tt>",不过效率更高。<P></LI></UL><P><H1><A NAME="SECTION006700000000000000000"></A><A NAME="defining"></A><BR>4.7 深入函数定义 More on Defining Functions </H1><P>It is also possible to define functions with a variable number of
arguments.  There are three forms, which can be combined.<P>有时需要定义参数个数可变的函数。有三个方法可以达到目的,我们可以组合使用它们。<P><H2><A NAME="SECTION006710000000000000000"></A><A NAME="defaultArgs"></A><BR>4.7.1 参数默认值 Default Argument Values </H2><P>The most useful form is to specify a default value for one or more
arguments.  This creates a function that can be called with fewer
arguments than it is defined to allow.  For example:<P>最有用的形式是给一个或多个参数指定默认值。这样创建的函数可以用较少的参数来调用。例如:<P><div class="verbatim"><pre>
def ask_ok(prompt, retries=4, complaint='Yes or no, please!'):
    while True:
        ok = raw_input(prompt)
        if ok in ('y', 'ye', 'yes'): return True
        if ok in ('n', 'no', 'nop', 'nope'): return False
        retries = retries - 1
        if retries &lt; 0: raise IOError, 'refusenik user'
        print complaint</pre></div><P>This function can be called either like this:
<code>ask_ok('Do you really want to quit?')</code> or like this:
<code>ask_ok('OK to overwrite the file?', 2)</code>.<P>这个函数还可以用以下的方式调用:<code>ask_ok('Do you really want
to quit?')</code>,或者像这样:<code>ask_ok('OK to overwrite the file?',
2)</code>。<P>This example also introduces the <tt class="keyword">in</tt> keyword. This tests
whether or not a sequence contains a certain value.<P>这个示例还介绍了关键字 <tt class="keyword">in</tt> 。它检测一个序列中是否包含某个给定的值。<P>The default values are evaluated at the point of function definition
in the <em>defining</em> scope, so that<P>默认值在函数<em>定义</em>段被解析,如下所示:<P><div class="verbatim"><pre>
i = 5

def f(arg=i):
    print arg

i = 6
f()</pre></div><P>will print <code>5</code>.<P>以上代码会打印5。<P><strong>Important warning:</strong>  The default value is evaluated only once.
This makes a difference when the default is a mutable object such as a
list, dictionary, or instances of most classes.  For example, the
following function accumulates the arguments passed to it on
subsequent calls:<P><strong>重要警告</strong>:默认值只会解析一次。当默认值是一个可变对象,诸如链表、字典或大部分类实例时,会产生一些差异。例如,以下函数在后继的调用中会累积它的参数值:<P><div class="verbatim"><pre>
def f(a, L=[]):
    L.append(a)
    return L

print f(1)
print f(2)
print f(3)</pre></div><P>This will print<P>这会打印出:<P><div class="verbatim"><pre>
[1]
[1, 2]
[1, 2, 3]</pre></div><P>If you don't want the default to be shared between subsequent calls,
you can write the function like this instead:<P>如果你不想在不同的函数调用之间共享参数默认值,可以如下面的实例一样编写函数:<P><div class="verbatim"><pre>
def f(a, L=None):
    if L is None:
        L = []
    L.append(a)
    return L</pre></div><P><H2><A NAME="SECTION006720000000000000000"></A><A NAME="keywordArgs"></A><BR>4.7.2 关键字参数 Keyword Arguments </H2><P>Functions can also be called using
keyword arguments of the form "<tt class="samp"><var>keyword</var> = <var>value</var></tt>".  For
instance, the following function:<P>函数可以通过关键字参数的形式来调用,形如"<tt class="samp"><var>keyword</var> = <var>value</var></tt>"。例如,以下的函数:<P><div class="verbatim"><pre>
def parrot(voltage, state='a stiff', action='voom', type='Norwegian Blue'):
    print "-- This parrot wouldn't", action,
    print "if you put", voltage, "Volts through it."
    print "-- Lovely plumage, the", type
    print "-- It's", state, "!"</pre></div><P>could be called in any of the following ways:<P>可以用以下的任一方法调用:<P>

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -