The last two expressions apply to totally ordered collections (e.g. to sequences, but not to sets or mappings). See also the total_ordering() decorator.

  • The hash() result should be consistent with equality. Objects that are equal should either have the same hash value, or be marked as unhashable.

  • Python does not enforce these consistency rules. In fact, the not-a-number values are an example for not following these rules.

    6.10.2. 成员资格测试操作

    运算符 in and not in 用于成员资格测试。 x in s 评估为 True if x 是成员对于 s ,和 False 否则。 x not in s 返回取反的 x in s . All built-in sequences and set types support this as well as dictionary, for which in tests whether the dictionary has a given key. For container types such as list, tuple, set, frozenset, dict, or collections.deque, the expression x in y 相当于 any(x is e or x == e for e in y) .

    对于字符串和字节类型, x in y is True if and only if x is a substring of y . An equivalent test is y.find(x) != -1 . Empty strings are always considered to be a substring of any other string, so "" in "abc" 将返回 True .

    For user-defined classes which define the __contains__() 方法, x in y 返回 True if y.__contains__(x) 返回 True 值,和 False 否则。

    For user-defined classes which do not define __contains__() but do define __iter__() , x in y is True if some value z , for which the expression x is z or x == z is true, is produced while iterating over y . If an exception is raised during the iteration, it is as if in raised that exception.

    Lastly, the old-style iteration protocol is tried: if a class defines __getitem__() , x in y is True if and only if there is a non-negative integer index i 这样 x is y[i] or x == y[i] , and no lower integer index raises the IndexError exception. (If any other exception is raised, it is as if in raised that exception).

    运算符 not in is defined to have the inverse truth value of in .

    6.10.3. 身份比较

    运算符 is and is not 测试对象身份: x is y 为 True 当且仅当 x and y are the same object. An Object’s identity is determined using the id() 函数。 x is not y yields the inverse truth value. [ 4 ]

    6.11. 布尔运算

    or_test  ::=  and_test | or_test "or" and_test
    and_test ::=  not_test | and_test "and" not_test
    not_test ::=  comparison | "not" not_test
    

    In the context of Boolean operations, and also when expressions are used by control flow statements, the following values are interpreted as false: False , None , numeric zero of all types, and empty strings and containers (including strings, tuples, lists, dictionaries, sets and frozensets). All other values are interpreted as true. User-defined objects can customize their truth value by providing a __bool__() 方法。

    运算符 not 产生 True 若其自变量为 False, False 否则。

    表达式 x and y 首先评估 x ;若 x is false, its value is returned; otherwise, y is evaluated and the resulting value is returned.

    表达式 x or y 首先评估 x ;若 x is true, its value is returned; otherwise, y is evaluated and the resulting value is returned.

    Note that neither and nor or restrict the value and type they return to False and True , but rather return the last evaluated argument. This is sometimes useful, e.g., if s is a string that should be replaced by a default value if it is empty, the expression s or 'foo' yields the desired value. Because not has to create a new value, it returns a boolean value regardless of the type of its argument (for example, not 'foo' produces False 而不是 '' )。

    6.12. 赋值表达式

    assignment_expression ::=  [identifier ":="] expression
    

    An assignment expression (sometimes also called a “named expression” or “walrus”) assigns an expression to an identifier , while also returning the value of the expression .

    One common use case is when handling matched regular expressions:

    if matching := pattern.search(data):
        do_something(matching)
    

    Or, when processing a file stream in chunks:

    while chunk := file.read(9000):
        process(chunk)
    

    Assignment expressions must be surrounded by parentheses when used as expression statements and when used as sub-expressions in slicing, conditional, lambda, keyword-argument, and comprehension-if expressions and in assert , with ,和 assignment statements. In all other places where they can be used, parentheses are not required, including in if and while 语句。

    Added in version 3.8: PEP 572 for more details about assignment expressions.

    6.13. 条件表达式

    conditional_expression ::=  or_test ["if" or_test "else" expression]
    expression             ::=  conditional_expression | lambda_expr
    

    条件表达式 (有时称为三元运算符) 在所有 Python 操作中拥有最低优先级。

    表达式 x if C else y 首先评估条件, C 而不是 x 。若 C 为 True, x is evaluated and its value is returned; otherwise, y is evaluated and its value is returned.

    PEP 308 了解条件表达式的有关更多细节。

    6.14. Lambda

    lambda_expr ::=  "lambda" [parameter_list] ":" expression
    

    lambda 表达式 (有时称为 lambda 形式) 用于创建匿名函数。表达式 lambda parameters: expression 产生函数对象。未命名对象的行为像定义函数对象采用:

    def <lambda>(parameters):
        return expression
    

    见章节 函数定义 了解参数列表的句法。注意:采用 Lambda 表达式创建的函数不可以包含语句 (或注解)。

    6.15. 表达式列表

    expression_list    ::=  expression ("," expression)* [","]
    starred_list       ::=  starred_item ("," starred_item)* [","]
    starred_expression ::=  expression | (starred_item ",")* [starred_item]
    starred_item       ::=  assignment_expression | "*" or_expr
    

    Except when part of a list or set display, an expression list containing at least one comma yields a tuple. The length of the tuple is the number of expressions in the list. The expressions are evaluated from left to right.

    星号 * 表示 可迭代解包 。它的操作数必须是 iterable . The iterable is expanded into a sequence of items, which are included in the new tuple, list, or set, at the site of the unpacking.

    Added in version 3.5: Iterable unpacking in expression lists, originally proposed by PEP 448 .

    A trailing comma is required only to create a one-item tuple, such as 1, ; it is optional in all other cases. A single expression without a trailing comma doesn’t create a tuple, but rather yields the value of that expression. (To create an empty tuple, use an empty pair of parentheses: () )。

    6.16. 评估次序

    Python evaluates expressions from left to right. Notice that while evaluating an assignment, the right-hand side is evaluated before the left-hand side.

    In the following lines, expressions will be evaluated in the arithmetic order of their suffixes:

    expr1, expr2, expr3, expr4
    (expr1, expr2, expr3, expr4)
    {expr1: expr2, expr3: expr4}
    expr1 + expr2 * (expr3 - expr4)
    expr1(expr2, expr3, *expr4, **expr5)
    expr3, expr4 = expr1, expr2
    

    6.17. 运算符优先级

    The following table summarizes the operator precedence in Python, from highest precedence (most binding) to lowest precedence (least binding). Operators in the same box have the same precedence. Unless the syntax is explicitly given, operators are binary. Operators in the same box group left to right (except for exponentiation and conditional expressions, which group from right to left).

    Note that comparisons, membership tests, and identity tests, all have the same precedence and have a left-to-right chaining feature as described in the 比较 章节。

    运算符

    描述

    (expressions...) ,

    [expressions...] , {key: value...} , {expressions...}

    Binding or parenthesized expression, list display, dictionary display, set display

    x[index] , x[index:index] , x(arguments...) , x.attribute

    Subscription, slicing, call, attribute reference

    await x

    await 表达式

    **

    取幂 [ 5 ]

    +x , -x , ~x

    正、负、按位非

    * , @ , / , // , %

    Multiplication, matrix multiplication, division, floor division, remainder [ 6 ]

    + , -

    加法和减法

    << , >>

    Shifts

    &

    按位 AND

    ^

    按位 XOR

    |

    按位 OR

    in , not in , is , is not , < , <= , > , >= , != , ==

    比较,包括成员资格测试和身份测试

    not x

    布尔 NOT

    and

    布尔 AND

    or

    布尔 OR

    if else

    条件表达式

    lambda

    Lambda 表达式

    :=

    赋值表达式

    脚注

    内容表

    上一话题

    5. 导入系统

    下一话题

    7. 简单语句

    本页