6.3 赋值语句 Assignment statements

Assignment statements are used to (re)bind names to values and to modify attributes or items of mutable objects:

赋值语句用来把名字(重新)捆绑到值,以及修改可变对象的属性或者项目:

assignment_stmt  ::=  (target_list "=")+ expression_list
target_list  ::=  target ("," target)* [","]
target  ::=  identifier
    | "(" target_list ")"
    | "[" target_list "]"
    | attributeref
    | subscription
    | slicing
Download entire grammar as text.

(See section 5.3 for the syntax definitions for the last three symbols.)

(上面后三项符号的语法定义参看5.3节)

An assignment statement evaluates the expression list (remember that this can be a single expression or a comma-separated list, the latter yielding a tuple) and assigns the single resulting object to each of the target lists, from left to right.

一个赋值语句对表达式序列求值 (还记得这可以是单个表达式或者一个逗号分隔的序列,后者导出一个元组),然后从左到右地将对象结果一一地赋给目的序列的每个对象。

Assignment is defined recursively depending on the form of the target (list). When a target is part of a mutable object (an attribute reference, subscription or slicing), the mutable object must ultimately perform the assignment and decide about its validity, and may raise an exception if the assignment is unacceptable. The rules observed by various types and the exceptions raised are given with the definition of the object types (see section 3.2).

依赖于目标(序列)的形式,赋值被递归地定义。当目标是一个可变对象的一部分(属性引用,下标,片断)的时候,该可变对象必须最终执行该赋值,决定其有效性,并且如果该赋值不可接受可能会抛出一个例外。不同类型以及抛出例外所遵循的规则在该对象类型的定义中给出(见3.2节)。

Assignment of an object to a target list is recursively defined as follows.

一个对象向一个目的序列的赋值递归地定义如下.

Assignment of an object to a single target is recursively defined as follows.

一个对象向单个目标的赋值递归地定义如下。

(In the current implementation, the syntax for targets is taken to be the same as for expressions, and invalid syntax is rejected during the code generation phase, causing less detailed error messages.)

(在当前的实现中,目标对象的语法被认为和表达式的语法相同,并且非法语法在代码生成期被拒绝,这导致缺少详细的错误信息)

WARNING: Although the definition of assignment implies that overlaps between the left-hand side and the right-hand side are `safe' (e.g., "a, b = b, a" swaps two variables), overlaps within the collection of assigned-to variables are not safe! For instance, the following program prints "[0, 2]":

警告:虽然赋值的定义隐含着左手边和右手边之间的重叠是“安全的”(比如,"a, b = b, a"交换两个变量),在所赋值变量间的重叠却是不安全的!例如,下面的程序打印出"[0, 2]":

x = [0, 1]
i = 0
i, x[i] = 1, 2
print x



子节目录