免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 3252 | 回复: 0
打印 上一主题 下一主题

Python 3.1.1 中英文对照版语言参考手册 - 复合语句 [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2010-01-02 14:39 |只看该作者 |倒序浏览
本章状态:自校完成
7. 复合语句(Compound statements)

Compound statements contain (groups of) other statements; they affect or control
the execution of those other statements in some way.  In general, compound
statements span multiple lines, although in simple incarnations a whole compound
statement may be contained in one line.
复合语句包含有其它语句(组)。它们以某种方式影响或控制其它语句的执行。一般地,复合语句会跨越多行,但一个完整的复合语句也可以简化在一行中。
The
if
,
while
and
for
statements implement
traditional control flow constructs.  
try
specifies exception
handlers and/or cleanup code for a group of statements, while the
with
statement allows the execution of initialization and
finalization code around a block of code.  Function and class definitions are
also syntactically compound statements.
if

while

for
语句实现了传统的控制结构。
try
语句为一组语句指定了异常处理器和/或清理(cleanup)代码。
with
语句允许为其内的代码提供初始化的清理(finalization)代码。函数定义和类定义在语法上也被看作复合语句。
Compound statements consist of one or more ‘clauses.’  A clause consists of a
header and a ‘suite.’  The clause headers of a particular compound statement are
all at the same indentation level. Each clause header begins with a uniquely
identifying keyword and ends with a colon.  A suite is a group of statements
controlled by a clause.  A suite can be one or more semicolon-separated simple
statements on the same line as the header, following the header’s colon, or it
can be one or more indented statements on subsequent lines.  Only the latter
form of suite can contain nested compound statements; the following is illegal,
mostly because it wouldn’t be clear to which
if
clause a following
else
clause would belong:
复合语句由一个或多个”子句”(clause)组成。一个子句由一个头和一个”语句序列”(suite)组成。一个具体复合语句内的所有子句头都具
有相同的缩进层次。每个子句“头”以一个唯一性标识关键字开始并以一个冒号结束。“语句序列”,是该子句所控制的一组语句,一个语句序列可以是与子句头处
于同一行的,在子句头冒号之后以分号分隔的多条简单语句,或者也可以是在后面连续行中缩进的语句。只有第二种情况下,子句序列才允许包括嵌套复合语句。下
面这样是非法的,这样处理大部分原因是不易判断
else
子句与前面的
if
子句的配对关系:
if test1: if test2: print(x)
Also note that the semicolon binds tighter than the colon in this context, so
that in the following example, either all or none of the
print()
calls are
executed:
也要注意在这样的上下文中分号的优先级比冒号高,所以在下面的例子中,要么执行全部的
print()
调用,要么一个也不执行:
if x  y  z: print(x); print(y); print(z)
Summarizing:
总结:
compound_stmt ::=  
if_stmt
                   |
while_stmt
                   |
for_stmt
                   |
try_stmt
                   |
with_stmt
                   |
funcdef
                   |
classdef
suite         ::=  
stmt_list
NEWLINE | NEWLINE INDENT
statement
+ DEDENT
statement    ::=  
stmt_list
NEWLINE |
compound_stmt
stmt_list    ::=  
simple_stmt
(";"
simple_stmt
)* [";"]
Note that statements always end in a NEWLINE possibly followed by a
DEDENT.  Also note that optional continuation clauses always begin with a
keyword that cannot start a statement, thus there are no ambiguities (the
‘dangling
else
‘ problem is solved in Python by requiring nested
if
statements to be indented).
注意语句结尾的 NEWLINE 之后可能还有一个 DEDENT ,注意可选的续行子句都是以不能开始另一个语句的关键字开头的,因此这里不存在歧义(”悬挂
else
问题”已经因为Python要求缩进嵌套语句而解决掉了)。
The formatting of the grammar rules in the following sections places each clause
on a separate line for clarity.
为了叙述清楚,以下章节中每个子句的语法规则格式都会分行列出。
7.1.
if
语句(The
if
statement)

The
if
statement is used for conditional execution:
if
语句用于条件执行:
if_stmt ::=  "if"
expression
":"
suite
             ( "elif"
expression
":"
suite
)*
             ["else" ":"
suite
]
It selects exactly one of the suites by evaluating the expressions one by one
until one is found to be true (see section
布尔运算(Boolean operations)
for the definition of
true and false); then that suite is executed (and no other part of the
if
statement is executed or evaluated).  If all expressions are
false, the suite of the
else
clause, if present, is executed.
它对表达式逐个求值, 直到其中一个为真时, 准确地选择相应的一个语句序列(对于真和假的定义参见
布尔运算(Boolean operations)
节),然后该执行语句序列(
if
语句的其它部分不会被执行和计算)。如果所有表达式都为假, 并且给出了
else
子句,那么将执行它包括的语句序列。
7.2.
while
语句(The
while
statement)

The
while
statement is used for repeated execution as long as an
expression is true:
while
用于重复执行,前提是条件表达式为真:
while_stmt ::=  "while"
expression
":"
suite
                ["else" ":"
suite
]
This repeatedly tests the expression and, if it is true, executes the first
suite; if the expression is false (which may be the first time it is tested) the
suite of the
else
clause, if present, is executed and the loop
terminates.
while
会重复地计算表达式的值, 并且如果为真,就执行第一个语句序列;如果为假(可能在第一次比较时),就执行else子句(如果给出)并退出循环。
A
break
statement executed in the first suite terminates the loop
without executing the
else
clause’s suite.  A
continue
statement executed in the first suite skips the rest of the suite and goes back
to testing the expression.
在第一个语句序列中执行
break
语句就可以做到不执行
else
子句而退出循环。在第一个语句序列执行
continue
语句可以跳过该子句的其余部分直接进入下次的表达式测试。
7.3.
for
语句(The
for
statement)

The
for
statement is used to iterate over the elements of a sequence
(such as a string, tuple or list) or other iterable object:
for
语句用于迭代有序类型(像串、元组或列表)或其它可迭代对象的元素:
for_stmt ::=  "for"
target_list
"in"
expression_list
":"
suite
              ["else" ":"
suite
]
The expression list is evaluated once; it should yield an iterable object.  An
iterator is created for the result of the expression_list.  The suite is
then executed once for each item provided by the iterator, in the order of
ascending indices.  Each item in turn is assigned to the target list using the
standard rules for assignments (see
赋值语句(Assignment statements)
), and then the suite is
executed.  When the items are exhausted (which is immediately when the sequence
is empty or an iterator raises a
StopIteration
exception), the suite in
the
else
clause, if present, is executed, and the loop terminates.
只计算一次 expression_list ,它应该生成一个迭代器对象。然后在迭代器每次提供一个元素时就会执行语句序列(suite)一次,元素按索引升序循环给出。每个元素使用标准的赋值规则(见
赋值语句(Assignment statements)
)依次赋给循环的 target_list ,然后执行语句序列。当迭代完毕后(当有序类型对象为空,或者迭代器抛出异常
StopIteration
时立即结束循环),就执行
else
子句(如果给出)中的语句序列,最后结束循环。
A
break
statement executed in the first suite terminates the loop
without executing the
else
clause’s suite.  A
continue
statement executed in the first suite skips the rest of the suite and continues
with the next item, or with the
else
clause if there was no next
item.
在第一个语句序列中执行
break
语句可以不执行
else
子句就退出循环。在第一个语句序列中执行
continue
语句可以跳过该子句的其余部分,直接处理下个元素,或者如果没有下个元素了,就进入
else
子句。
The suite may assign to the variable(s) in the target list; this does not affect
the next item assigned to it.
语句序列可以对 target_list 中的变量赋值,这不影响
for
语句赋下一项元素给它。
Names in the target list are not deleted when the loop is finished, but if the
sequence is empty, it will not have been assigned to at all by the loop.  Hint:
the built-in function
range()
returns an iterator of integers suitable to
emulate the effect of Pascal’s for i := a to b do; e.g., list(range(3))
returns the list [0, 1, 2].
在循环结束后,这个 target_list 并不会删除,但如果有序类型对象为空,它根本就不会在循环中赋值。小技巧:内置函数
range()
返回一个整数列表, 可以用于模拟Pascal语言中的 for i := a to b 的行为,例如 list(range(3)) 返回列表 [0, 1, 2] 。
Note
There is a subtlety when the sequence is being modified by the loop (this can
only occur for mutable sequences, i.e. lists).  An internal counter is used
to keep track of which item is used next, and this is incremented on each
iteration.  When this counter has reached the length of the sequence the loop
terminates.  This means that if the suite deletes the current (or a previous)
item from the sequence, the next item will be skipped (since it gets the
index of the current item which has already been treated).  Likewise, if the
suite inserts an item in the sequence before the current item, the current
item will be treated again the next time through the loop. This can lead to
nasty bugs that can be avoided by making a temporary copy using a slice of
the whole sequence, e.g., :
警告:如果在循环中要修改有序类型对象(仅对可变类型而言,
即列表),这里有一些要注意的地方。有一个内部计数器用于跟踪下一轮循环使用哪一个元素,并且每次迭代就增加一次。当这个计数器到达有序类型对象的长度时
该循环就结束了。这意味着如果语句序列删除了当前元素(或一个之前的元素)时,下一个元素就会被跳过去(因为当前索引值的元素已经处理过了)。类似地,如
果在当前元素前插入了一个元素,则当前元素会在下一轮循环再次得到处理。这可能会导致难以觉察的错误,但可以通过使用含有整个有序类型对象的片断而生成的
临时拷贝避免这个问题,例如:
for x in a[:]:
    if x  0: a.remove(x)
7.4.
try
语句(The
try
statement)

The
try
statement specifies exception handlers and/or cleanup code
for a group of statements:
try
语句为一组语句指定异常处理器和/或清理代码:
try_stmt ::=  try1_stmt | try2_stmt
try1_stmt ::=  "try" ":"
suite
               ("except" [
expression
["as"
target
]] ":"
suite
)+
               ["else" ":"
suite
]
               ["finally" ":"
suite
]
try2_stmt ::=  "try" ":"
suite
               "finally" ":"
suite
The
except
clause(s) specify one or more exception handlers. When no
exception occurs in the
try
clause, no exception handler is executed.
When an exception occurs in the
try
suite, a search for an exception
handler is started.  This search inspects the except clauses in turn until one
is found that matches the exception.  An expression-less except clause, if
present, must be last; it matches any exception.  For an except clause with an
expression, that expression is evaluated, and the clause matches the exception
if the resulting object is “compatible” with the exception.  An object is
compatible with an exception if it is the class or a base class of the exception
object or a tuple containing an item compatible with the exception.
except
子句指定了一个或多个异常处理器。当在
try
子句中没有异常发生时,异常处理器将不被执行。当在
try
子句中有异常发生时,就会开始搜索异常处理器。它会按书写顺序搜索每个子句,直到有一个匹配的处理器找到为止。如果存在一个没有指定异常的
except
子句,它必须放在最后,它会匹配任何异常。当一个
except
子句携带了一个表达式时,这个表达式会被求值,如果结果与该异常”兼容”,那么该子句就匹配上了这个异常。对象与异常兼容是指,对象与这个异常的类或者基类相同,或者对象是一个元组,它的某个项包括与该异常兼容的对象。
If no except clause matches the exception, the search for an exception handler
continues in the surrounding code and on the invocation stack.  
[1]
如果没有
except
子句匹配异常,异常处理器的搜索工作将继续在外层代码和调用栈上进行。
If the evaluation of an expression in the header of an except clause raises an
exception, the original search for a handler is canceled and a search starts for
the new exception in the surrounding code and on the call stack (it is treated
as if the entire
try
statement raised the exception).
如果在
except
子句头部计算表达式时引发了异常,那么就会中断原异常处理器的搜索工作,而在外层代码和调用栈上搜索新的异常处理器(就好像是整个
try
语句发生了异常一样)。
When a matching except clause is found, the exception is assigned to the target
specified after the
as
keyword in that except clause, if present, and
the except clause’s suite is executed.  All except clauses must have an
executable block.  When the end of this block is reached, execution continues
normally after the entire try statement.  (This means that if two nested
handlers exist for the same exception, and the exception occurs in the try
clause of the inner handler, the outer handler will not handle the exception.)
当找到了一个匹配的
except
子句时,异常对象就被赋给
except
子句中关键字
as
指定的目标对象(如果给出), 并且执行其
后的语句序列。每个
except
子句必须一个可执行代码块。当执行到该代码块末尾时,会跳转到整个
try
语句之后继续正常执行(这意味着, 如果有两个嵌套的异常处理器要处理同一个异常的话,那么如果异常已经在内层处理了,外层处理器就不会响应这个异常了)。
When an exception has been assigned using as target, it is cleared at the
end of the except clause.  This is as if :
在使用 as target 形式将异常赋值时,它会在
except
子句结束时自动清除掉:
except E as N:
    foo
was translated to :
被转换为:
except E as N:
    try:
        foo
    finally:
        N = None
        del N
That means that you have to assign the exception to a different name if you want
to be able to refer to it after the except clause.  The reason for this is that
with the traceback attached to them, exceptions will form a reference cycle with
the stack frame, keeping all locals in that frame alive until the next garbage
collection occurs.
这意味着如果你想在
except
子句结束之后仍然要访问这个异常的话,必须在处理它时把它赋给另一个名字的变量。这么设计的原因在于回溯过程会关联上它们,异常和栈桢一起会构成一个引用循环,从而使栈桢上所有局部变量不被回收,直到下次垃圾回收时。
Before an except clause’s suite is executed, details about the exception are
stored in the
sys
module and can be access via
sys.exc_info()
.
sys.exc_info()
returns a 3-tuple consisting of: exc_type, the
exception class; exc_value, the exception instance; exc_traceback, a
traceback object (see section
标准类型层次(The standard type hierarchy)
) identifying the point in the program
where the exception occurred.
sys.exc_info()
values are restored to their
previous values (before the call) when returning from a function that handled an
exception.
在某个
except
子句的语句序列被执行前,异常的详细情况记录在
sys
模块中,可以通过函数
sys.exc_info()
访问。
sys.exc_info()
返回一个元组,包括 exc_type ,异常类; exc_value ,异常实例; exc_traceback ,记录异常发生点的回溯对象(见
标准类型层次(The standard type hierarchy)
)。
sys.exc_info()
值会在处理异常的函数返回时会恢复它们之前的值(调用之前)。
The optional
else
clause is executed if and when control flows off
the end of the
try
clause.
[2]
Exceptions in the
else
clause are not handled by the preceding
except
clauses.
当控制从
try
子句的尾部结束时(即没有异常发生时),就执行可选的
else
子句。在
else
子句中引发的异常不会在前面的
except
子句里得到处理。
If
finally
is present, it specifies a ‘cleanup’ handler.  The
try
clause is executed, including any
except
and
else
clauses.  If an exception occurs in any of the clauses and is
not handled, the exception is temporarily saved. The
finally
clause
is executed.  If there is a saved exception, it is re-raised at the end of the
finally
clause. If the
finally
clause raises another
exception or executes a
return
or
break
statement, the
saved exception is lost.  The exception information is not available to the
program during execution of the
finally
clause.
如果给出了
finally
,它就指定一个”清理”处理器(cleanup handler)。这种语法下,
try
子句会得到执行,也包括任何
except

else
子句。如果在任何子句中发生了异常,并且这个异常没有得到处理,该异常就会被临时保存起来。之后,
finally
子句就会得以执行。然后暂存的异常在
finally
子句末尾被重新引发。如果执行
finally
子句时引发了另一个异常或执行了:keyword:return 或
break
语句,就会抛弃保存的异常。在执行
finally
子句时异常信息是无效的。
When a
return
,
break
or
continue
statement is
executed in the
try
suite of a
try
...
finally
statement, the
finally
clause is also executed ‘on the way out.’ A
continue
statement is illegal in the
finally
clause. (The
reason is a problem with the current implementation — this restriction may be
lifted in the future).
当在
try
...
finally
语句中的
try
语句序列中执行
return

break

continue
  时,
finally
子句也会“在退出的路上”被执行。在
finally
子句中的
continue
语句是非法的(这缘于因为当前实现中的一个问题——以后可能会去掉这个限制)。
Additional information on exceptions can be found in section
异常(Exceptions)
,
and information on using the
raise
statement to generate exceptions
may be found in section
The raise statement
.
关于异常的更多信息可以在
异常(Exceptions)
中找到,关于如何使用
raise
语句产生异常的信息,可以在
The raise statement
中找到。
7.5.
with
语句(The
with
statement)

The
with
statement is used to wrap the execution of a block with
methods defined by a context manager (see section
with语句的上下文管理器(With Statement Context Managers)
).
This allows common
try
...
except
...
finally
usage patterns to be encapsulated for convenient reuse.
with
语句用于封装上下文管理器(见
with语句的上下文管理器(With Statement Context Managers)
)定义的方法的代码块的执行。这允许我们方便地复用常见的
try
...
except
...
finally
使用模式。
with_stmt ::=  "with" with_item ("," with_item)* ":"
suite
with_item ::=  
expression
["as"
target
]
The execution of the statement with one “item” proceeds as follows:
with
语句对一个 “item” 的执行按如下方式进行:
  • The context expression is evaluated to obtain a context manager.
    对上下文表达式求值得到一个上下文管理器。
  • The context manager’s
    __enter__()
    method is invoked.
    调用上下文管理器的
    __enter__()
    方法。
  • If a target was included in the
    with
    statement, the return value
    from
    __enter__()
    is assigned to it.
    如果
    with
    语句包括有 target ,就将
    __enter__()
    的返回值赋给它。
    Note
    The
    with
    statement guarantees that if the
    __enter__()
    method returns without an error, then
    __exit__()
    will always be
    called.  Thus, if an error occurs during the assignment to the target
    list, it will be treated the same as an error occurring within the suite
    would be.  See step 5 below.
    with
    语句保证了如果
    __enter__()
    是无错返回的,就一定会调用
    __exit__()
    方法。如果在给 target list 赋值时发生错误,就按在语句序列里发生错误同样对待,参见下面的步骤5。
  • The suite is executed.
    执行语句序列。
  • The context manager’s
    __exit__()
    method is invoked.  If an exception
    caused the suite to be exited, its type, value, and traceback are passed as
    arguments to
    __exit__()
    . Otherwise, three
    None
    arguments are
    supplied.
    调用上下文管理器的
    __exit__()
    方法。如果语句序列导致了一个异常,那么异常的异常的类型,值和回溯对象都作为参数传递给
    __exit__()
    方法。否则,使用
    None
    作为参数。
    If the suite was exited due to an exception, and the return value from the
    __exit__()
    method was false, the exception is reraised.  If the return
    value was true, the exception is suppressed, and execution continues with the
    statement following the
    with
    statement.
    如果语句序列因为异常退出,且
    __exit__()
    方法返回假,那么异常就会重新抛出。如果返回值为真,异常就会被“吃掉”,并且执行会在
    with
    语句之后继续。
    If the suite was exited for any reason other than an exception, the return
    value from
    __exit__()
    is ignored, and execution proceeds at the normal
    location for the kind of exit that was taken.
    如果语句序列不是因为异常的原因退出的,那么
    __exit__()
    的返回值会被忽略掉,并且在退出点后继续运行程序。
    With more than one item, the context managers are processed as if multiple
    with
    statements were nested:
    使用多个项时,上下文管理器就按多个嵌套
    with
    语句处理:
    with A() as a, B() as b:
        suite
    is equivalent to :
    等价于:
    with A() as a:
        with B() as b:
            suite
    Changed in version 3.1: Support for multiple context expressions.
    See also
    PEP 0343
    - The “with” statementThe specification, background, and examples for the Python
    with
    statement.
    Python
    with
    语句的规范、背景和例子。
    7.6. 函数定义(Function definitions)

    A function definition defines a user-defined function object (see section
    标准类型层次(The standard type hierarchy)
    ):
    “函数定义”定义了一个用户定义函数对象(见
    标准类型层次(The standard type hierarchy)
    ):
    funcdef       ::=  [
    decorators
    ] "def"
    funcname
    "(" [
    parameter_list
    ] ")" ["->"
    expression
    ] ":"
    suite
    decorators    ::=  
    decorator
    +
    decorator      ::=  "@"
    dotted_name
    ["(" [
    argument_list
    [","]] ")"] NEWLINE
    dotted_name    ::=  
    identifier
    ("."
    identifier
    )*
    parameter_list ::=  (
    defparameter
    ",")*
                        (  "*" [
    parameter
    ] (","
    defparameter
    )*
                        [, "**"
    parameter
    ]
                        | "**"
    parameter
                        |
    defparameter
    [","] )
    parameter      ::=  
    identifier
    [":"
    expression
    ]
    defparameter   ::=  
    parameter
    ["="
    expression
    ]
    funcname       ::=  
    identifier
    A function definition is an executable statement.  Its execution binds the
    function name in the current local namespace to a function object (a wrapper
    around the executable code for the function).  This function object contains a
    reference to the current global namespace as the global namespace to be used
    when the function is called.
    函数定义是一个可执行语句。执行它会在当前局部名字空间中将函数名字与函数对象(一个函数可执行代码的包装对象)绑定在一起。这个函数对象包括一个全局名字空间的引用,以便在调用时使用。
    The function definition does not execute the function body; this gets executed
    only when the function is called.
    [3]
    函数定义不执行函数体,它们只在调用时执行。
    A function definition may be wrapped by one or more
    decorator
    expressions.
    Decorator expressions are evaluated when the function is defined, in the scope
    that contains the function definition.  The result must be a callable, which is
    invoked with the function object as the only argument. The returned value is
    bound to the function name instead of the function object.  Multiple decorators
    are applied in nested fashion. For example, the following code :
    函数定义前可能有若干个
    decorator
    表达式。Decorator表达式于函数定义时,且在函数定义所在的作用域里求值。结果必须是可调用的,它以函数对象为唯一参数,然后它的返回值将与函数名绑定,而不是函数对象本身。多个Decorator表达式可以嵌套使用,例如,以下代码:
    @f1(arg)
    @f2
    def func(): pass
    is equivalent to :
    等价于:
    def func(): pass
    func = f1(arg)(f2(func))
    When one or more parameters have the form parameter = expression, the
    function is said to have “default parameter values.”  For a parameter with a
    default value, the corresponding argument may be omitted from a call, in which
    case the parameter’s default value is substituted.  If a parameter has a default
    value, all following parameters up until the “*” must also have a default
    value — this is a syntactic restriction that is not expressed by the grammar.
    当一个或多个参数以 parameter = expression 形式出现时,我们就说这个函数具有”默认参数值”。对于有默认参数值的参数,可以在调用时省略它们,此时他们被赋予默认值。如果某参数具有默认值, 则它之后直到 “*” 的所有参数都必须有默认值 —— 这是以上语法说明中没有表达出来的一个限制。
    Default parameter values are evaluated when the function definition is
    executed.
    This means that the expression is evaluated once, when the function
    is defined, and that that same “pre-computed” value is used for each call.  This
    is especially important to understand when a default parameter is a mutable
    object, such as a list or a dictionary: if the function modifies the object
    (e.g. by appending an item to a list), the default value is in effect modified.
    This is generally not what was intended.  A way around this is to use None
    as the default, and explicitly test for it in the body of the function, e.g.:
    默认参数值是在执行函数定义时计算的。
    这意味着这个表达式仅仅求值一次,时间是函数定义时,并且所有调用都使用这个”预计算”的值。在理解默认参数值是一个像列表、字典这样的可变对象时,这需
    要特别注意:如果修改了这个对象(例如给列表追加了一项),默认值也随之修改。这通常是应该避免的。避免这个麻烦的一个方法就是使用 None 作默认值,然后在函数体中作显式的测试,例如:
    def whats_on_the_telly(penguin=None):
        if penguin is None:
            penguin = []
        penguin.append("property of the zoo")
        return penguin
    Function call semantics are described in more detail in section
    调用(Calls)
    . A
    function call always assigns values to all parameters mentioned in the parameter
    list, either from position arguments, from keyword arguments, or from default
    values.  If the form “*identifier” is present, it is initialized to a tuple
    receiving any excess positional parameters, defaulting to the empty tuple.  If
    the form “**identifier” is present, it is initialized to a new dictionary
    receiving any excess keyword arguments, defaulting to a new empty dictionary.
    Parameters after “*” or “*identifier” are keyword-only parameters and
    may only be passed used keyword arguments.
    函数调用语义的详细说明,参见
    调用(Calls)
    一节。函数调用通常会给每个参数表中的参数赋一个值,值的来源要么是位置参数、要么是关键字参数或者是默认值。如果给出了  “*identifier” 语法,这个标识符就被初始化成一个接受所有额外位置参数的元组,默认为空元组。如果使用了 “**identifier” 语法,它就被初始化成一个接受所有额外关键字参数的字典,默认为一个新的空字典。在 “*” or “*identifier” 之后的参数必须是纯关键字参数,并且只能使用指定关键字的方式传递。
    Parameters may have annotations of the form “: expression” following the
    parameter name.  Any parameter may have an annotation even those of the form
    *identifier or **identifier.  Functions may have “return” annotation of
    the form “-> expression” after the parameter list.  These annotations can be
    any valid Python expression and are evaluated when the function definition is
    executed.  Annotations may be evaluated in a different order than they appear in
    the source code.  The presence of annotations does not change the semantics of a
    function.  The annotation values are available as values of a dictionary keyed
    by the parameters’ names in the __annotations__ attribute of the
    function object.
    可以使用参数名之后 “: expression” 语法为参数添加一个注解。任何参数都可以有注解,甚至包括 *identifier 或 **identifier 。函数也可以有一个“返回“注解,语法是在参数列表之后使用 “-> expression” 。这些注解可以是任何合法的Python表达式,它是在函数定义时求值的,但它们的求值顺序可能与在源代码中的书写顺序不同。使用注解不会改变函数的语义,注解的值可以通过函数对象的属性 __annotations__ 访问,它是一个字典,键是参数名字。
    It is also possible to create anonymous functions (functions not bound to a
    name), for immediate use in expressions.  This uses lambda forms, described in
    section
    Lambdas
    .  Note that the lambda form is merely a shorthand for a
    simplified function definition; a function defined in a “
    def

    statement can be passed around or assigned to another name just like a function
    defined by a lambda form.  The “
    def
    ” form is actually more powerful
    since it allows the execution of multiple statements and annotations.
    也可以创建匿名函数(没有名字与之绑定的函数),它可以直接在表达式中使用。这是通过lambda表达式实现的,详见
    Lambdas
    。注意lambda形式只是一个简单函数的简写形式,以
    def
    定义的函数也可以被传递、或者赋予另一个名字,与以lambda定义的函数一样。以
    def
    定义的函数功能要更强大些,因为它允许执行多条语句和注解。
    Programmer’s note: Functions are first-class objects.  A “def” form
    executed inside a function definition defines a local function that can be
    returned or passed around.  Free variables used in the nested function can
    access the local variables of the function containing the def.  See section
    名字与绑定(Naming and binding)
    for details.
    程序员注意: 在函数定义中执行的
    def
    可以创建一个局部函数,可用于返回和传递。在嵌套函数里,可以通过自由变量访问包括这个函数定义的函数的局部变量。详见
    名字与绑定(Naming and binding)

    7.7. 类定义(Class definitions)

    A class definition defines a class object (see section
    标准类型层次(The standard type hierarchy)
    ):
    “类定义”定义一个类对象(参见
    标准类型层次(The standard type hierarchy)
    ):
    classdef    ::=  [
    decorators
    ] "class"
    classname
    [
    inheritance
    ] ":"
    suite
    inheritance ::=  "(" [
    expression_list
    ] ")"
    classname   ::=  
    identifier
    A class definition is an executable statement.  It first evaluates the
    inheritance list, if present.  Each item in the inheritance list should evaluate
    to a class object or class type which allows subclassing.  The class’s suite is
    then executed in a new execution frame (see section
    名字与绑定(Naming and binding)
    ), using a
    newly created local namespace and the original global namespace. (Usually, the
    suite contains only function definitions.)  When the class’s suite finishes
    execution, its execution frame is discarded but its local namespace is
    saved.
    [4]
    A class object is then created using the inheritance list for the
    base classes and the saved local namespace for the attribute dictionary.  The
    class name is bound to this class object in the original local namespace.
    类定义是一个可执行语句。它首先对继承关系表(如果存在)求值。继承关系表中的每项的求值结果都应该是一个类对象,或者是支持子类化的对象。然后类的语句序列在新的栈桢结构(见
    名字与绑定(Naming and binding)
    )内执行,它会使用新创建的局部名字空间和原来的全局名字空间(通常这个语句序列里只有函数定义)。当这个语句序执行结束时,就会丢弃掉这个栈桢结构,但
    其局部名字空间被保存了下来。之后,使用其继承关系表创建基类和保存下来的名字空间作为属性字典创建新的类对象。类名字会被绑定在最初名字空间中的类对象
    上。
    Classes can also be decorated; as with functions, :
    类也可以使用decorate表达式,类似于函数:
    @f1(arg)
    @f2
    class Foo: pass
    is equivalent to :
    等价于:
    class Foo: pass
    Foo = f1(arg)(f2(Foo))
    Programmer’s note: Variables defined in the class definition are class
    variables; they are shared by instances. Instance variables can be set in a
    method with self.name = value.  Both class and instance variables are
    accessible through the notation “self.name“, and an instance variable hides
    a class variable with the same name when accessed in this way.  Class variables
    can be used as defaults for instance variables, but using mutable values there
    can lead to unexpected results.  Descriptors can be used to create instance
    variables with different implementation details.
    程序员注意: 在类定义中定义的变量是类变量,它们由所有类实例共享。实例变量可以使用 self.name = value 设置值。实例变量和类变量都可以使用这种方式访问,但实例变量会掩盖掉类变量。类变量可以用于实例变量的默认值,但使用可变对象可能带来未知的结果,还可以使用描述符创建具有不同实现的实例变量。
    See also
    PEP 3129
    - Class Decorators
    Class definitions, like function definitions, may be wrapped by one or more
    decorator
    expressions.  The evaluation rules for the decorator
    expressions are the same as for functions.  The result must be a class object,
    which is then bound to the class name.
    和函数定义一样,类定义也可以使用一个或多个
    decorator
    表达式包装。它们的求值规则与函数相同,但其结果必须是一个类对象,与类名绑定。
    脚注(Footnotes)
    [1]
    The exception is propagated to the invocation stack only if there is no
    finally
    clause that negates the exception.
    只有在
    finally
    子句没有取消(negate)异常时,异常才会传播出调用栈。
    [2]
    Currently, control “flows off the end” except in the case of an exception or the
    execution of a
    return
    ,
    continue
    , or
    break
    statement.
    目前,尾部结束(”flows off the end”) 不包括出现异常的情况,以及执行
    return

    continue

    break
    语句的情况。
    [3]
    A string literal appearing as the first statement in the function body is
    transformed into the function’s __doc__ attribute and therefore the
    function’s
    docstring
    .
    在函数体作为第一条语句出现的字符串字面值,会被转换为函数的 __doc__ 属性,即作为函数的
    docstring

    [4]
    A string literal appearing as the first statement in the class body is
    transformed into the namespace’s __doc__ item and therefore the class’s
    docstring
    .
    在类定义中作为第一条语句出现的字符串字面值,会被转换为名字空间的项 __doc__ ,即作为类的
    docstring

                   
                   
                   

    本文来自ChinaUnix博客,如果查看原文请点:http://blog.chinaunix.net/u1/42957/showart_2137541.html
  • 您需要登录后才可以回帖 登录 | 注册

    本版积分规则 发表回复

      

    北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
    未成年举报专区
    中国互联网协会会员  联系我们:huangweiwei@itpub.net
    感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

    清除 Cookies - ChinaUnix - Archiver - WAP - TOP