4. More Control Flow Tools更多控制流工具

Besides the while statement just introduced, Python uses the usual flow control statements known from other languages, with some twists.除了刚才介绍的while语句外,Python还使用了其他语言中常见的流控制语句,但有些曲折。

4.1. if Statements语句

Perhaps the most well-known statement type is the if statement. 也许最著名的语句类型是if语句。For example:例如:

>>> x = int(input("Please enter an integer: "))
Please enter an integer: 42
>>> if x < 0:
... x = 0
... print('Negative changed to zero')
... elif x == 0:
... print('Zero')
... elif x == 1:
... print('Single')
... else:
... print('More')
...
More

There can be zero or more elif parts, and the else part is optional. 可以有零个或多个elif部件,而else部件是可选的。The keyword ‘elif’ is short for ‘else if’, and is useful to avoid excessive indentation. 关键字“elif”是“else if”的缩写,用于避免过度缩进。An ifelifelif … sequence is a substitute for the switch or case statements found in other languages.if-elif-elif序列可以替代其他语言中的switchcase语句。

If you’re comparing the same value to several constants, or checking for specific types or attributes, you may also find the match statement useful. 如果要将同一个值与多个常量进行比较,或检查特定类型或属性,则还可能会发现match语句很有用。For more details see match Statements.有关更多详细信息,请参阅match语句

4.2. for Statements语句

The for statement in Python differs a bit from what you may be used to in C or Pascal. Python中的for语句与C或Pascal中的for语句有点不同。Rather than always iterating over an arithmetic progression of numbers (like in Pascal), or giving the user the ability to define both the iteration step and halting condition (as C), Python’s for statement iterates over the items of any sequence (a list or a string), in the order that they appear in the sequence. Python的for语句并不是总是迭代一个算术数列(如Pascal),也不是让用户能够定义迭代步骤和停止条件(如C),而是按照它们在序列中出现的顺序迭代任何序列的项(列表或字符串)。For example (no pun intended):例如(没有双关语):

>>> # Measure some strings:
... words = ['cat', 'window', 'defenestrate']
>>> for w in words:
... print(w, len(w))
...
cat 3
window 6
defenestrate 12

Code that modifies a collection while iterating over that same collection can be tricky to get right. 在对同一集合进行迭代时修改该集合的代码可能很难正确执行。Instead, it is usually more straight-forward to loop over a copy of the collection or to create a new collection:相反,在集合的副本上循环或创建新集合通常更直接:

# Create a sample collection
users = {'Hans': 'active', 'Éléonore': 'inactive', '景太郎': 'active'}
# Strategy: Iterate over a copy
for user, status in users.copy().items():
if status == 'inactive':
del users[user]

# Strategy: Create a new collection
active_users = {}
for user, status in users.items():
if status == 'active':
active_users[user] = status

4.3. The range() Functionrange()函数

If you do need to iterate over a sequence of numbers, the built-in function range() comes in handy. 如果确实需要迭代一个数字序列,内置函数range()很方便。It generates arithmetic progressions:它生成算术级数:

>>> for i in range(5):
... print(i)
...
0
1
2
3
4

The given end point is never part of the generated sequence; range(10) generates 10 values, the legal indices for items of a sequence of length 10. 给定的终点永远不是生成序列的一部分;range(10)生成10个值,即长度为10的序列项的法定索引。It is possible to let the range start at another number, or to specify a different increment (even negative; sometimes this is called the ‘step’):可以让范围从另一个数字开始,或者指定不同的增量(甚至是负数;有时这被称为“步长”):

>>> list(range(5, 10))
[5, 6, 7, 8, 9]
>>> list(range(0, 10, 3))
[0, 3, 6, 9]

>>> list(range(-10, -100, -30))
[-10, -40, -70]

To iterate over the indices of a sequence, you can combine range() and len() as follows:要迭代序列的索引,可以按如下方式组合range()len()

>>> a = ['Mary', 'had', 'a', 'little', 'lamb']
>>> for i in range(len(a)):
... print(i, a[i])
...
0 Mary
1 had
2 a
3 little
4 lamb

In most such cases, however, it is convenient to use the enumerate() function, see Looping Techniques.然而,在大多数情况下,使用enumerate()函数很方便,请参阅循环技术

A strange thing happens if you just print a range:如果只打印一个范围,就会发生一件奇怪的事情:

>>> range(10)
range(0, 10)

In many ways the object returned by range() behaves as if it is a list, but in fact it isn’t. 在许多方面,range()返回的对象的行为就像它是一个列表,但事实并非如此。It is an object which returns the successive items of the desired sequence when you iterate over it, but it doesn’t really make the list, thus saving space.它是一个对象,当你遍历它时,它会返回所需序列的连续项,但它实际上并不在列表中,因此节省了空间。

We say such an object is iterable, that is, suitable as a target for functions and constructs that expect something from which they can obtain successive items until the supply is exhausted. 我们说这样的对象是可迭代的,也就是说,适合作为函数和结构的目标,这些函数和结构期望从中获得连续的项目,直到供应耗尽。We have seen that the for statement is such a construct, while an example of a function that takes an iterable is sum():我们已经看到for语句就是这样一种构造,而接受可迭代的函数的一个例子是sum()

>>> sum(range(4))  # 0 + 1 + 2 + 3
6

Later we will see more functions that return iterables and take iterables as arguments. 稍后我们将看到更多返回可迭代对象并将可迭代对象作为参数的函数。In chapter Data Structures, we will discuss in more detail about list().数据结构一章中,我们将更详细地讨论list()

4.4. break and continue Statements, and else Clauses on Loopsbreak语句和continue语句,以及循环上的else语句

The break statement, like in C, breaks out of the innermost enclosing for or while loop.break语句与C中的语句一样,脱离了最内部的forwhile循环。

Loop statements may have an else clause; it is executed when the loop terminates through exhaustion of the iterable (with for) or when the condition becomes false (with while), but not when the loop is terminated by a break statement. 循环语句可能有一个else子句;当循环通过耗尽可迭代对象(使用for)或当条件变为false(使用while)而终止时执行,但当循环通过break语句终止时不执行。This is exemplified by the following loop, which searches for prime numbers:下面的循环就是一个例子,它搜索素数:

>>> for n in range(2, 10):
... for x in range(2, n):
... if n % x == 0:
... print(n, 'equals', x, '*', n//x)
... break
... else:
... # loop fell through without finding a factor
... print(n, 'is a prime number')
...
2 is a prime number
3 is a prime number
4 equals 2 * 2
5 is a prime number
6 equals 2 * 3
7 is a prime number
8 equals 2 * 4
9 equals 3 * 3

(Yes, this is the correct code. Look closely: the else clause belongs to the for loop, not the if statement.)(是的,这是正确的代码。仔细看:else子句从属于for循环,而不是从属于if语句。)

When used with a loop, the else clause has more in common with the else clause of a try statement than it does with that of if statements: a try statement’s else clause runs when no exception occurs, and a loop’s else clause runs when no break occurs. 当与循环一起使用时,else子句与try语句的else子句比与if语句的else子句有更多共同之处:try语句的子句在没有异常发生时运行,而循环的else子句在没有break发生时运行。For more on the try statement and exceptions, see Handling Exceptions.有关try语句和异常的更多信息,请参阅处理异常

The continue statement, also borrowed from C, continues with the next iteration of the loop:continue语句也是从C中借用的,它继续循环的下一次迭代:

>>> for num in range(2, 10):
... if num % 2 == 0:
... print("Found an even number", num)
... continue
... print("Found an odd number", num)
...
Found an even number 2
Found an odd number 3
Found an even number 4
Found an odd number 5
Found an even number 6
Found an odd number 7
Found an even number 8
Found an odd number 9

4.5. pass Statements语句

The pass statement does nothing. pass语句没有任何作用。It can be used when a statement is required syntactically but the program requires no action. 在语法上需要语句,但程序不需要操作时,可以使用它。For example:例如:

>>> while True:
... pass # Busy-wait for keyboard interrupt (Ctrl+C)
...

This is commonly used for creating minimal classes:这通常用于创建最小类:

>>> class MyEmptyClass:
... pass
...

Another place pass can be used is as a place-holder for a function or conditional body when you are working on new code, allowing you to keep thinking at a more abstract level. pass还可用于在编写新代码时作为函数或条件体的占位符,使您能够在更抽象的层次上思考。The pass is silently ignored:pass被悄悄忽略:

>>> def initlog(*args):
... pass # Remember to implement this!
...

4.6. match Statements语句

A match statement takes an expression and compares its value to successive patterns given as one or more case blocks. match语句接受一个表达式,并将其值与作为一个或多个case块给出的连续模式进行比较。This is superficially similar to a switch statement in C, Java or JavaScript (and many other languages), but it can also extract components (sequence elements or object attributes) from the value into variables.这在表面上类似于C、Java或JavaScript(以及许多其他语言)中的switch语句,但它也可以将组件(序列元素或对象属性)从值提取到变量中。

The simplest form compares a subject value against one or more literals:最简单的形式是将主题值与一个或多个文本进行比较:

def http_error(status):
match status:
case 400:
return "Bad request"
case 404:
return "Not found"
case 418:
return "I'm a teapot"
case _:
return "Something's wrong with the internet"

Note the last block: the “variable name” _ acts as a wildcard and never fails to match. 请注意最后一个块:“变量名”_充当通配符,永远不会不匹配。If no case matches, none of the branches is executed.如果没有case匹配,则不会执行任何分支。

You can combine several literals in a single pattern using | (“or”):可以使用|(“或”)将多个文本组合成一个模式:

case 401 | 403 | 404:
return "Not allowed"

Patterns can look like unpacking assignments, and can be used to bind variables:模式可以看起来像解包赋值,可以用来绑定变量:

# point is an (x, y) tuple
match point:
case (0, 0):
print("Origin")
case (0, y):
print(f"Y={y}")
case (x, 0):
print(f"X={x}")
case (x, y):
print(f"X={x}, Y={y}")
case _:
raise ValueError("Not a point")

Study that one carefully! 仔细研究那个!The first pattern has two literals, and can be thought of as an extension of the literal pattern shown above. 第一个模式有两个文本,可以认为是上面所示文本模式的扩展。But the next two patterns combine a literal and a variable, and the variable binds a value from the subject (point). 但接下来的两种模式结合了文字和变量,变量绑定了来自主题(point)的值。The fourth pattern captures two values, which makes it conceptually similar to the unpacking assignment (x, y) = point.第四种模式捕获两个值,这使得它在概念上类似于解包赋值(x, y) = point

If you are using classes to structure your data you can use the class name followed by an argument list resembling a constructor, but with the ability to capture attributes into variables:如果使用类来构造数据,则可以使用类名后跟类似构造函数的参数列表,但可以将属性捕获到变量中:

class Point:
x: int
y: int
def where_is(point):
match point:
case Point(x=0, y=0):
print("Origin")
case Point(x=0, y=y):
print(f"Y={y}")
case Point(x=x, y=0):
print(f"X={x}")
case Point():
print("Somewhere else")
case _:
print("Not a point")

You can use positional parameters with some builtin classes that provide an ordering for their attributes (e.g. dataclasses). 您可以将位置参数用于一些内置类,这些类为属性(例如dataclasses)提供排序。You can also define a specific position for attributes in patterns by setting the __match_args__ special attribute in your classes. 还可以通过在类中设置__match_args__特殊属性来定义模式中属性的特定位置。If it’s set to (“x”, “y”), the following patterns are all equivalent (and all bind the y attribute to the var variable):如果设置为(“x”、“y”),则以下模式都是等效的(并且都将y属性绑定到var变量):

Point(1, var)
Point(1, y=var)
Point(x=1, y=var)
Point(y=var, x=1)

A recommended way to read patterns is to look at them as an extended form of what you would put on the left of an assignment, to understand which variables would be set to what. 阅读模式的一种推荐方法是将其视为作业左侧内容的扩展形式,以了解哪些变量将被设置为什么。Only the standalone names (like var above) are assigned to by a match statement. match语句只为独立名称(如上面的var)赋值。Dotted names (like foo.bar), attribute names (the x= and y= above) or class names (recognized by the “(…)” next to them like Point above) are never assigned to.虚线名称(比如foo.bar)、属性名称(上面的x=y=)或类名(通过它们旁边的“(…)”识别,比如上面的Point)永远不会被分配给它。

Patterns can be arbitrarily nested. 模式可以任意嵌套。For example, if we have a short list of points, we could match it like this:例如,如果我们有一个简短的点列表,我们可以这样匹配:

match points:
case []:
print("No points")
case [Point(0, 0)]:
print("The origin")
case [Point(x, y)]:
print(f"Single point {x}, {y}")
case [Point(0, y1), Point(0, y2)]:
print(f"Two on the Y axis at {y1}, {y2}")
case _:
print("Something else")

We can add an if clause to a pattern, known as a “guard”. 我们可以在模式中添加一个if子句,称为“守卫”。If the guard is false, match goes on to try the next case block. 如果守卫是假的,match继续尝试下一个case块。Note that value capture happens before the guard is evaluated:请注意,值捕获发生在对保护进行评估之前:

match point:
case Point(x, y) if x == y:
print(f"Y=X at {x}")
case Point(x, y):
print(f"Not on the diagonal")

Several other key features of this statement:该语句的其他几个关键特征:

  • Like unpacking assignments, tuple and list patterns have exactly the same meaning and actually match arbitrary sequences. 与解包赋值一样,元组和列表模式具有完全相同的含义,并且实际上匹配任意序列。An important exception is that they don’t match iterators or strings.一个重要的例外是,它们与迭代器或字符串不匹配。

  • Sequence patterns support extended unpacking: [x, y, *rest] and (x, y, *rest) work similar to unpacking assignments. 序列模式支持扩展解包:[x, y, *rest](x, y, *rest)的工作方式与解包任务类似。The name after * may also be _, so (x, y, *_) matches a sequence of at least two items without binding the remaining items.*后面的名称也可以是_,因此(x, y, *_)匹配至少两个项的序列,而不绑定其余项。

  • Mapping patterns: {"bandwidth": b, "latency": l} captures the "bandwidth" and "latency" values from a dictionary. 映射模式:{"bandwidth": b, "latency": l}从字典中捕获"bandwidth""latency"值。Unlike sequence patterns, extra keys are ignored. 与序列模式不同,额外的键被忽略。An unpacking like **rest is also supported. 还支持像**rest这样的解包。(But **_ would be redundant, so it is not allowed.)(但是**_是多余的,所以是不允许的。)

  • Subpatterns may be captured using the as keyword:可以使用as关键字捕获子模式:

    case (Point(x1, y1), Point(x2, y2) as p2): ...

    will capture the second element of the input as p2 (as long as the input is a sequence of two points)将输入的第二个元素捕获为p2(只要输入是两点序列)

  • Most literals are compared by equality, however the singletons True, False and None are compared by identity.大多数文字是通过相等来比较的,但是单例TrueFalseNone是通过身份来比较的。

  • Patterns may use named constants. 模式可以使用命名常量。These must be dotted names to prevent them from being interpreted as capture variable:这些名称必须是虚线名称,以防止它们被解释为捕获变量:

    from enum import Enum
    class Color(Enum):
    RED = 'red'
    GREEN = 'green'
    BLUE = 'blue'
    color = Color(input("Enter your choice of 'red', 'blue' or 'green': "))

    match color:
    case Color.RED:
    print("I see red!")
    case Color.GREEN:
    print("Grass is green")
    case Color.BLUE:
    print("I'm feeling the blues :(")

For a more detailed explanation and additional examples, you can look into PEP 636 which is written in a tutorial format.要获得更详细的解释和其他示例,您可以查看以教程格式编写的PEP 636

4.7. Defining Functions定义函数

We can create a function that writes the Fibonacci series to an arbitrary boundary:我们可以创建一个函数,将斐波那契级数写入任意边界:

>>> def fib(n):    # write Fibonacci series up to n
... """Print a Fibonacci series up to n."""
... a, b = 0, 1
... while a < n:
... print(a, end=' ')
... a, b = b, a+b
... print()
...
>>> # Now call the function we just defined:
... fib(2000)
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597

The keyword def introduces a function definition. 关键字def引入函数定义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 documentation string, or docstring. 函数体的第一条语句可以是字符串文字;此字符串文字是函数的文档字符串或docstring(More about docstrings can be found in the section Documentation Strings.) (有关docstrings的更多信息,请参阅文档字符串一节。)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 make a habit of it.有一些工具使用docstring自动生成在线或打印文档,或者让用户以交互方式浏览代码;在您编写的代码中包含docstring是一种很好的做法,所以要养成习惯。

The execution 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 local symbol tables of enclosing functions, then in the global symbol table, and finally in the table of built-in names. 更准确地说,函数中的所有变量赋值都将值存储在局部符号表中;而变量引用首先在局部符号表中查找,然后在封闭函数的局部符号表中查找,然后在全局符号表中查找,最后在内置名称表中查找。Thus, global variables and variables of enclosing functions cannot be directly assigned a value within a function (unless, for global variables, named in a global statement, or, for variables of enclosing functions, named in a nonlocal statement), although they may be referenced.因此,全局变量和封闭函数的变量不能在函数中直接赋值(除非全局变量在global语句中命名,或封闭函数的变量在nonlocal语句中命名),尽管它们可以被引用。

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 call by value (where the value is always an object reference, not the value of the object). 函数调用的实际参数(参数)在被调用函数的本地符号表中引入;因此,使用按值调用传递参数(其中始终是对象引用,而不是对象的值)。1 When a function calls another function, or calls itself recursively, a new local symbol table is created for that call.当一个函数调用另一个函数或递归调用自身时,会为该调用创建一个新的本地符号表。

A function definition associates the function name with the function object in the current symbol table. 函数定义将函数名称与当前符号表中的函数对象相关联。The interpreter recognizes the object pointed to by that name as a user-defined function. 解释器将该名称指向的对象识别为用户定义的函数。Other names can also point to that same function object and can also be used to access the function:其他名称也可以指向同一个函数对象,也可以用于访问该函数:

>>> fib
<function fib at 10042ed0>
>>> f = fib
>>> f(100)
0 1 1 2 3 5 8 13 21 34 55 89

Coming from other languages, you might object that fib is not a function but a procedure since it doesn’t return a value. 来自其他语言,您可能会反对称fib不是一个函数,而是一个过程,因为它不返回值。In fact, even functions without a return statement do return a value, albeit a rather boring one. 事实上,即使没有return语句的函数也会返回一个值,尽管这是一个相当无聊的值。This value is called None (it’s a built-in name). 该值称为None(它是一个内置名称)。Writing the value None is normally suppressed by the interpreter if it would be the only value written. 写入值None通常会被解释器抑制,如果它是唯一写入的值。You can see it if you really want to using print():如果你真的想使用print(),你可以看到它:

>>> fib(0)
>>> print(fib(0))
None

It is simple to write a function that returns a list of the numbers of the Fibonacci series, instead of printing it:编写一个函数,返回斐波那契数列的数字列表,而不是打印它,这很简单:

>>> 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 a < n:
... result.append(a) # see below
... a, b = b, a+b
... return result
...
>>> f100 = fib2(100) # call it
>>> f100 # write the result
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]

This example, as usual, demonstrates some new Python features:与往常一样,这个示例演示了一些新的Python特性:

  • The return statement returns with a value from a function. return语句从函数返回一个值。return without an expression argument returns None. 不带表达式参数的return返回NoneFalling off the end of a function also returns None.从函数末尾掉下来也会返回None

  • The statement result.append(a) calls a method of the list object result. 语句result.append(a)调用列表对象result的一个方法A method is a function that ‘belongs’ to an object and is named obj.methodname, where obj is some object (this may be an expression), and methodname is the name of a method that is defined by the object’s type. 方法是一个“从属于”对象的函数,名为obj.methodname,其中obj是某个对象(这可能是一个表达式),methodname是由对象类型定义的方法的名称。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 classes, see Classes.) (可以使用定义自己的对象类型和方法,请参阅。)The method append() shown in the example is defined for list objects; it adds a new element at the end of the list. 示例中所示的append()方法是为列表对象定义的;它会在列表的末尾添加一个新元素。In this example it is equivalent to result = result + [a], but more efficient.在本例中,它相当于result = result+[a],但效率更高。

4.8. More on Defining Functions更多关于定义函数的信息

It is also possible to define functions with a variable number of arguments. 也可以定义参数数量可变的函数。There are three forms, which can be combined.有三种形式可以组合。

4.8.1. Default Argument Values默认参数值

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:例如:

def ask_ok(prompt, retries=4, reminder='Please try again!'):
while True:
ok = input(prompt)
if ok in ('y', 'ye', 'yes'):
return True
if ok in ('n', 'no', 'nop', 'nope'):
return False
retries = retries - 1
if retries < 0:
raise ValueError('invalid user response')
print(reminder)

This function can be called in several ways:可以通过几种方式调用此函数:

  • giving only the mandatory argument: 仅给出强制参数:ask_ok('Do you really want to quit?')

  • giving one of the optional arguments: 给出一个可选参数:ask_ok('OK to overwrite the file?', 2)

  • or even giving all arguments: 甚至给出所有参数:ask_ok('OK to overwrite the file?', 2, 'Come on, only yes or no!')

This example also introduces the in keyword. 本例还引入了in关键字。This tests whether or not a sequence contains a certain value.这将测试序列是否包含特定值。

The default values are evaluated at the point of function definition in the defining scope, so that默认值在定义范围内的函数定义点进行计算,以便

i = 5
def f(arg=i):
print(arg)

i = 6
f()

will print 5.将打印5

Important warning:重要警告: 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:例如,以下函数累积在后续调用中传递给它的参数:

def f(a, L=[]):
L.append(a)
return L
print(f(1))
print(f(2))
print(f(3))

This will print这会打印出来

[1]
[1, 2]
[1, 2, 3]

If you don’t want the default to be shared between subsequent calls, you can write the function like this instead:如果不希望在后续调用之间共享默认值,可以这样编写函数:

def f(a, L=None):
if L is None:
L = []
L.append(a)
return L

4.8.2. Keyword Arguments关键字参数

Functions can also be called using keyword arguments of the form kwarg=value. 也可以使用kwarg=value形式的关键字参数调用函数。For instance, the following function:例如,以下函数:

def parrot(voltage, state='a stiff', action='voom', type='Norwegian Blue'):
print("-- This parrot wouldn't", action, end=' ')
print("if you put", voltage, "volts through it.")
print("-- Lovely plumage, the", type)
print("-- It's", state, "!")

accepts one required argument (voltage) and three optional arguments (state, action, and type). 接受一个必需参数(voltage)和三个可选参数(stateactiontype)。This function can be called in any of the following ways:可以通过以下任一方式调用此函数:

parrot(1000)                                          # 1 positional argument
parrot(voltage=1000) # 1 keyword argument
parrot(voltage=1000000, action='VOOOOOM') # 2 keyword arguments
parrot(action='VOOOOOM', voltage=1000000) # 2 keyword arguments
parrot('a million', 'bereft of life', 'jump') # 3 positional arguments
parrot('a thousand', state='pushing up the daisies') # 1 positional, 1 keyword

but all the following calls would be invalid:但以下所有调用都将无效:

parrot()                     # required argument missing
parrot(voltage=5.0, 'dead') # non-keyword argument after a keyword argument
parrot(110, voltage=220) # duplicate value for the same argument
parrot(actor='John Cleese') # unknown keyword argument

In a function call, keyword arguments must follow positional arguments. 在函数调用中,关键字参数必须跟在位置参数后面。All the keyword arguments passed must match one of the arguments accepted by the function (e.g. actor is not a valid argument for the parrot function), and their order is not important. 传递的所有关键字参数必须与函数接受的参数之一匹配(例如,actor不是parrot函数的有效参数),并且它们的顺序并不重要。This also includes non-optional arguments (e.g. parrot(voltage=1000) is valid too). 这还包括非可选参数(例如parrot(voltage=1000)也有效)。No argument may receive a value more than once. Here’s an example that fails due to this restriction:任何参数都不能多次收到值。以下是一个因该限制而失败的示例:

>>> def function(a):
... pass
...
>>> function(0, a=0)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: function() got multiple values for argument 'a'

When a final formal parameter of the form **name is present, it receives a dictionary (see Mapping Types — dict) containing all keyword arguments except for those corresponding to a formal parameter. **name形式的最后一个形式参数出现时,它会收到一个字典(请参见映射类型字典),其中包含除与形式参数对应的关键字参数之外的所有关键字参数。This may be combined with a formal parameter of the form *name (described in the next subsection) which receives a tuple containing the positional arguments beyond the formal parameter list. 这可以与形式*name(在下一小节中描述)的形式参数相结合,该形式参数接收包含形式参数列表之外的位置参数的元组(*name must occur before **name.) *name必须出现在**name之前。)For example, if we define a function like this:例如,如果我们定义这样一个函数:

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)
for kw in keywords:
print(kw, ":", keywords[kw])

It could be called like this:可以这样调用它:

cheeseshop("Limburger", "It's very runny, sir.",
"It's really very, VERY runny, sir.",
shopkeeper="Michael Palin",
client="John Cleese",
sketch="Cheese Shop Sketch")

and of course it would print:当然,它会打印:

-- 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.
----------------------------------------
shopkeeper : Michael Palin
client : John Cleese
sketch : Cheese Shop Sketch

Note that the order in which the keyword arguments are printed is guaranteed to match the order in which they were provided in the function call.请注意,关键字参数的打印顺序保证与函数调用中提供它们的顺序相匹配。

4.8.3. Special parameters特殊参数

By default, arguments may be passed to a Python function either by position or explicitly by keyword. 默认情况下,参数可以通过位置传递给Python函数,也可以通过关键字显式传递给Python函数。For readability and performance, it makes sense to restrict the way arguments can be passed so that a developer need only look at the function definition to determine if items are passed by position, by position or keyword, or by keyword.为了提高可读性和性能,有必要限制参数的传递方式,以便开发人员只需查看函数定义即可确定是按位置、位置或关键字还是按关键字传递项。

A function definition may look like:函数定义可能如下所示:

def f(pos1, pos2, /, pos_or_kwd, *, kwd1, kwd2):
----------- ---------- ----------
| | |
| Positional or keyword |
| - Keyword only
-- Positional only

where / and * are optional. 其中/*是可选的。If used, these symbols indicate the kind of parameter by how the arguments may be passed to the function: positional-only, positional-or-keyword, and keyword-only. Keyword parameters are also referred to as named parameters.如果使用,这些符号通过参数传递给函数的方式指示参数的类型:仅位置、位置或关键字和仅关键字。关键字参数也称为命名参数。

4.8.3.1. Positional-or-Keyword Arguments位置或关键字参数

If / and * are not present in the function definition, arguments may be passed to a function by position or by keyword.如果函数定义中不存在/*,则可以通过位置或关键字将参数传递给函数。

4.8.3.2. Positional-Only Parameters位置参数

Looking at this in a bit more detail, it is possible to mark certain parameters as positional-only. 更详细地看一下,可以将某些参数标记为位置参数。If positional-only, the parameters’ order matters, and the parameters cannot be passed by keyword. Positional-only parameters are placed before a / (forward-slash). 如果只是位置参数,那么参数的顺序很重要,不能通过关键字传递参数。仅位置参数放置在/(正斜杠)之前。The / is used to logically separate the positional-only parameters from the rest of the parameters. /用于从逻辑上将仅位置参数与其余参数分开。If there is no / in the function definition, there are no positional-only parameters.如果函数定义中没有/,则不存在仅位置参数。

Parameters following the / may be positional-or-keyword or keyword-only./后面的参数可以是位置或关键字参数或关键字参数。

4.8.3.3. Keyword-Only Arguments关键字参数

To mark parameters as keyword-only, indicating the parameters must be passed by keyword argument, place an * in the arguments list just before the first keyword-only parameter.要将参数标记为仅关键字,指示参数必须通过关键字参数传递,请在参数列表中仅在第一个仅关键字参数之前放置一个*

4.8.3.4. Function Examples函数示例

Consider the following example function definitions paying close attention to the markers / and *:考虑以下示例函数定义,密切关注标记/*

>>> def standard_arg(arg):
... print(arg)
...
>>> def pos_only_arg(arg, /):
... print(arg)
...
>>> def kwd_only_arg(*, arg):
... print(arg)
...
>>> def combined_example(pos_only, /, standard, *, kwd_only):
... print(pos_only, standard, kwd_only)

The first function definition, standard_arg, the most familiar form, places no restrictions on the calling convention and arguments may be passed by position or keyword:第一个函数定义standard_arg是最常见的形式,它对调用约定没有任何限制,参数可以通过位置或关键字传递:

>>> standard_arg(2)
2
>>> standard_arg(arg=2)
2

The second function pos_only_arg is restricted to only use positional parameters as there is a / in the function definition:第二个函数pos_only_arg仅限于使用位置参数,因为函数定义中有一个/

>>> pos_only_arg(1)
1
>>> pos_only_arg(arg=1)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: pos_only_arg() got some positional-only arguments passed as keyword arguments: 'arg'

The third function kwd_only_args only allows keyword arguments as indicated by a * in the function definition:第三个函数kwd_only_args只允许函数定义中用*表示的关键字参数:

>>> kwd_only_arg(3)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: kwd_only_arg() takes 0 positional arguments but 1 was given
>>> kwd_only_arg(arg=3)
3

And the last uses all three calling conventions in the same function definition:最后一个在同一个函数定义中使用了所有三种调用约定:

>>> combined_example(1, 2, 3)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: combined_example() takes 2 positional arguments but 3 were given
>>> combined_example(1, 2, kwd_only=3)
1 2 3

>>> combined_example(1, standard=2, kwd_only=3)
1 2 3

>>> combined_example(pos_only=1, standard=2, kwd_only=3)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: combined_example() got some positional-only arguments passed as keyword arguments: 'pos_only'

Finally, consider this function definition which has a potential collision between the positional argument name and **kwds which has name as a key:最后,考虑这个函数定义,它可能会在位置参数name**kwds之间发生冲突,后者以name作为键:

def foo(name, **kwds):
return 'name' in kwds

There is no possible call that will make it return True as the keyword 'name' will always bind to the first parameter. 没有可能的调用会使其返回True,因为关键字'name'将始终绑定到第一个参数。For example:例如:

>>> foo(1, **{'name': 2})
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: foo() got multiple values for argument 'name'
>>>

But using / (positional only arguments), it is possible since it allows name as a positional argument and 'name' as a key in the keyword arguments:但是使用/(仅位置参数)是可能的,因为它允许name作为位置参数,而'name'作为关键字参数中的键:

def foo(name, /, **kwds):
return 'name' in kwds
>>> foo(1, **{'name': 2})
True

In other words, the names of positional-only parameters can be used in **kwds without ambiguity.换句话说,仅位置参数的名称可以在**kwds中使用,不会产生歧义。

4.8.3.5. Recap扼要重述

The use case will determine which parameters to use in the function definition:用例将决定在函数定义中使用哪些参数:

def f(pos1, pos2, /, pos_or_kwd, *, kwd1, kwd2):

As guidance:作为指导:

  • Use positional-only if you want the name of the parameters to not be available to the user. 仅当希望参数的名称对用户不可用时,才使用“位置”。This is useful when parameter names have no real meaning, if you want to enforce the order of the arguments when the function is called or if you need to take some positional parameters and arbitrary keywords.当参数名没有实际意义时,如果您想在调用函数时强制执行参数的顺序,或者如果您需要获取一些位置参数和任意关键字,这将非常有用。

  • Use keyword-only when names have meaning and the function definition is more understandable by being explicit with names or you want to prevent users relying on the position of the argument being passed.仅当名称有意义且函数定义更易于理解时才使用关键字,因为名称更明确,或者您希望防止用户依赖传递的参数的位置。

  • For an API, use positional-only to prevent breaking API changes if the parameter’s name is modified in the future.对于API,如果参数的名称在将来被修改,请仅使用“位置”来防止中断API更改。

4.8.4. Arbitrary Argument Lists任意参数列表

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 (see Tuples and Sequences). 这些参数将封装在一个元组中(参见元组和序列)。Before the variable number of arguments, zero or more normal arguments may occur.在参数数量可变之前,可能会出现零个或多个正常参数。

def write_multiple_items(file, separator, *args):
file.write(separator.join(args))

Normally, these variadic arguments will be last in the list of formal parameters, because they scoop up all remaining input arguments that are passed to the function. 通常情况下,这些可变参数将是形式参数列表中的最后一个参数,因为它们会收集传递给函数的所有剩余输入参数。Any formal parameters which occur after the *args parameter are ‘keyword-only’ arguments, meaning that they can only be used as keywords rather than positional arguments.在*args参数之后出现的任何形式参数都是“仅关键字”参数,这意味着它们只能用作关键字,而不是位置参数。

>>> def concat(*args, sep="/"):
... return sep.join(args)
...
>>> concat("earth", "mars", "venus")
'earth/mars/venus'
>>> concat("earth", "mars", "venus", sep=".")
'earth.mars.venus'

4.8.5. Unpacking Argument Lists解包参数列表

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 range() function expects separate start and stop arguments. 例如,内置的range()函数需要单独的startstop参数。If they are not available separately, write the function call with the *-operator to unpack the arguments out of a list or tuple:如果它们不能单独使用,请使用*-运算符编写函数调用,以将参数从列表或元组中解包出来:

>>> list(range(3, 6))            # normal call with separate arguments
[3, 4, 5]
>>> args = [3, 6]
>>> list(range(*args)) # call with arguments unpacked from a list
[3, 4, 5]

In the same fashion, dictionaries can deliver keyword arguments with the **-operator:同样,字典可以通过**-运算符传递关键字参数:

>>> def parrot(voltage, state='a stiff', action='voom'):
... print("-- This parrot wouldn't", action, end=' ')
... print("if you put", voltage, "volts through it.", end=' ')
... print("E's", state, "!")
...
>>> d = {"voltage": "four million", "state": "bleedin' demised", "action": "VOOM"}
>>> parrot(**d)
-- This parrot wouldn't VOOM if you put four million volts through it. E's bleedin' demised !

4.8.6. Lambda Expressions表达式

Small anonymous functions can be created with the lambda keyword. 可以使用lambda关键字创建小型匿名函数。This function returns the sum of its two arguments: lambda a, b: a+b. 此函数返回其两个参数之和:lambda a, b: a+bLambda functions can be used wherever function objects are required. Lambda函数可以在任何需要函数对象的地方使用。They are syntactically restricted to a single expression. 它们在语法上仅限于一个表达式。Semantically, they are just syntactic sugar for a normal function definition. 在语义上,它们只是普通函数定义的语法糖。Like nested function definitions, lambda functions can reference variables from the containing scope:与嵌套函数定义一样,lambda函数可以引用包含范围中的变量:

>>> def make_incrementor(n):
... return lambda x: x + n
...
>>> f = make_incrementor(42)
>>> f(0)
42
>>> f(1)
43

The above example uses a lambda expression to return a function. 上面的示例使用lambda表达式返回函数。Another use is to pass a small function as an argument:另一个用途是将一个小函数作为参数传递:

>>> pairs = [(1, 'one'), (2, 'two'), (3, 'three'), (4, 'four')]
>>> pairs.sort(key=lambda pair: pair[1])
>>> pairs
[(4, 'four'), (1, 'one'), (3, 'three'), (2, 'two')]

4.8.7. Documentation Strings文档字符串

Here are some conventions about the content and formatting of documentation strings.以下是关于文档字符串的内容和格式的一些约定。

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.这一行应该以大写字母开头,以句号结尾。

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.以下几行应该是一个或多个段落,描述对象的调用约定、副作用等。

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. Python解析器不会从Python中的多行字符串文本中去除缩进,因此处理文档的工具必须根据需要去除缩进。This is done using the following convention. 这是使用以下约定完成的。The first non-blank line after 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).空格的等价性应该在扩展制表符后进行测试(通常为8个空格)。

Here is an example of a multi-line docstring:以下是多行docstring的示例:

>>> 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.

4.8.8. Function Annotations函数注解

Function annotations are completely optional metadata information about the types used by user-defined functions (see PEP 3107 and PEP 484 for more information).函数注释是关于用户定义函数使用的类型的完全可选元数据信息(有关更多信息,请参阅PEP 3107PEP 484)。

Annotations are stored in the __annotations__ attribute of the function as a dictionary and have no effect on any other part of the function. 注释作为字典存储在函数的__annotations__属性中,对函数的任何其他部分都没有影响。Parameter annotations are defined by a colon after the parameter name, followed by an expression evaluating to the value of the annotation. 参数注释由参数名称后的冒号定义,后跟计算注释值的表达式。Return annotations are defined by a literal ->, followed by an expression, between the parameter list and the colon denoting the end of the def statement. 返回注释由参数列表和表示def语句结束的冒号之间的文本->和表达式定义。The following example has a required argument, an optional argument, and the return value annotated:以下示例包含一个必需参数、一个可选参数和带注释的返回值:

>>> def f(ham: str, eggs: str = 'eggs') -> str:
... print("Annotations:", f.__annotations__)
... print("Arguments:", ham, eggs)
... return ham + ' and ' + eggs
...
>>> f('spam')
Annotations: {'ham': <class 'str'>, 'return': <class 'str'>, 'eggs': <class 'str'>}
Arguments: spam eggs
'spam and eggs'

4.9. Intermezzo: Coding Style间奏曲:编码风格

Now that you are about to write longer, more complex pieces of Python, it is a good time to talk about coding style. 现在,您将要编写更长、更复杂的Python片段,现在是讨论编码风格的好时机。Most languages can be written (or more concise, formatted) in different styles; some are more readable than others. 大多数语言可以用不同的风格书写(或者简称为格式化);有些比其他更具可读性。Making it easy for others to read your code is always a good idea, and adopting a nice coding style helps tremendously for that.让别人更容易阅读你的代码总是一个好主意,而采用一种好的编码风格对这一点非常有帮助。

For Python, PEP 8 has emerged as the style guide that most projects adhere to; it promotes a very readable and eye-pleasing coding style. 对于Python来说,PEP 8已经成为大多数项目所遵循的风格指南;它促进了一种可读性强、赏心悦目的编码风格。Every Python developer should read it at some point; here are the most important points extracted for you:每个Python开发人员都应该在某个时候阅读它;以下是最重要的要点:

  • Use 4-space indentation, and no tabs.使用四格缩进,不使用制表符。

    4 spaces are a good compromise between small indentation (allows greater nesting depth) and large indentation (easier to read). 4个空格是小缩进(允许更大的嵌套深度)和大缩进(更容易阅读)之间的一个很好的折衷。Tabs introduce confusion, and are best left out.标签会引起混乱,最好不要使用。

  • Wrap lines so that they don’t exceed 79 characters.换行,使其不超过79个字符。

    This helps users with small displays and makes it possible to have several code files side-by-side on larger displays.这有助于用户使用小屏幕,并使多个代码文件可以并排显示在大屏幕上。

  • Use blank lines to separate functions and classes, and larger blocks of code inside functions.使用空行分隔函数和类,并在函数内部使用更大的代码块。

  • When possible, put comments on a line of their own.如果可能的话,把评论放在自己的一行上。

  • Use docstrings.使用docstring。

  • Use spaces around operators and after commas, but not directly inside bracketing constructs: a = f(1, 2) + g(3, 4).在运算符周围和逗号之后使用空格,但不要直接在括号结构内部使用:a = f(1, 2) + g(3, 4)

  • Name your classes and functions consistently; the convention is to use UpperCamelCase for classes and lowercase_with_underscores for functions and methods. 统一命名你的类和函数;惯例是对类使用大写字母,对函数和方法使用带有下划线的小写字母Always use self as the name for the first method argument (see A First Look at Classes for more on classes and methods).始终使用self作为第一个方法参数的名称(有关类和方法的更多信息,请参阅初探类)。

  • Don’t use fancy encodings if your code is meant to be used in international environments. 如果你的代码要在国际环境中使用,不要使用花哨的编码。Python’s default, UTF-8, or even plain ASCII work best in any case.Python的默认值UTF-8,甚至是普通的ASCII,在任何情况下都是最好的。

  • Likewise, don’t use non-ASCII characters in identifiers if there is only the slightest chance people speaking a different language will read or maintain the code.同样,如果说不同语言的人很可能会阅读或维护代码,那么不要在标识符中使用非ASCII字符。

Footnotes

1

Actually, call by object reference 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).实际上,按对象引用调用是更好的描述,因为如果传递了一个可变对象,调用者将看到被调用者对其所做的任何更改(插入列表中的项目)。