# SOME DESCRIPTIVE TITLE. # Copyright (C) 2001-2024, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: # Fred , 2020 # eric R , 2020 # Woko , 2020 # df2dc1c92e792f7ae8417c51df43db8f_594d92a <0f49be28017426edb1db1a2ab6e67088_717605>, 2020 # ppcfish , 2020 # Rafael Fontenelle , 2024 # Freesand Leo , 2024 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.8\n" "Report-Msgid-Bugs-To: \n" "POT-Creation-Date: 2024-05-24 17:08+0000\n" "PO-Revision-Date: 2020-05-30 12:16+0000\n" "Last-Translator: Freesand Leo , 2024\n" "Language-Team: Chinese (China) (https://app.transifex.com/python-doc/teams/5390/zh_CN/)\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" "Language: zh_CN\n" "Plural-Forms: nplurals=1; plural=0;\n" #: ../../tutorial/controlflow.rst:5 msgid "More Control Flow Tools" msgstr "更多控制流工具" #: ../../tutorial/controlflow.rst:7 msgid "" "Besides the :keyword:`while` statement just introduced, Python uses the " "usual flow control statements known from other languages, with some twists." msgstr "除了上一章介绍的 :keyword:`while` 语句,Python 还支持其他语言中常见的流程控制语句,只是稍有不同。" #: ../../tutorial/controlflow.rst:14 msgid ":keyword:`!if` Statements" msgstr ":keyword:`!if` 语句" #: ../../tutorial/controlflow.rst:16 msgid "" "Perhaps the most well-known statement type is the :keyword:`if` statement. " "For example::" msgstr "最让人耳熟能详的语句应当是 :keyword:`if` 语句:" #: ../../tutorial/controlflow.rst:33 msgid "" "There can be zero or more :keyword:`elif` parts, and the :keyword:`else` " "part is optional. The keyword ':keyword:`!elif`' is short for 'else if', " "and is useful to avoid excessive indentation. An :keyword:`!if` ... " ":keyword:`!elif` ... :keyword:`!elif` ... sequence is a substitute for the " "``switch`` or ``case`` statements found in other languages." msgstr "" "可有零个或多个 :keyword:`elif` 部分,:keyword:`else` 部分也是可选的。关键字 ':keyword:`!elif`' 是 " "'else if' 的缩写,用于避免过多的缩进。:keyword:`!if` ... :keyword:`!elif` ... " ":keyword:`!elif` ... 序列可以当作其它语言中 ``switch`` 或 ``case`` 语句的替代品。" #: ../../tutorial/controlflow.rst:43 msgid ":keyword:`!for` Statements" msgstr ":keyword:`!for` 语句" #: ../../tutorial/controlflow.rst:48 msgid "" "The :keyword:`for` statement in Python differs a bit from what you may be " "used to in C or Pascal. 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 " ":keyword:`!for` statement iterates over the items of any sequence (a list or" " a string), in the order that they appear in the sequence. For example (no " "pun intended):" msgstr "" "Python 的 :keyword:`for` 语句与 C 或 Pascal 中的不同。Python 的 :keyword:`!for` " "语句不迭代算术递增数值(如 Pascal),或是给予用户定义迭代步骤和结束条件的能力(如 " "C),而是在列表或字符串等任意序列的元素上迭代,按它们在序列中出现的顺序。 例如(这不是有意要暗指什么):" #: ../../tutorial/controlflow.rst:69 msgid "" "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::" msgstr "很难正确地在迭代多项集的同时修改多项集的内容。更简单的方法是迭代多项集的副本或者创建新的多项集:" #: ../../tutorial/controlflow.rst:88 msgid "The :func:`range` Function" msgstr ":func:`range` 函数" #: ../../tutorial/controlflow.rst:90 msgid "" "If you do need to iterate over a sequence of numbers, the built-in function " ":func:`range` comes in handy. It generates arithmetic progressions::" msgstr "内置函数 :func:`range` 用于生成等差数列:" #: ../../tutorial/controlflow.rst:102 msgid "" "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." " 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')::" msgstr "" "生成的序列绝不会包括给定的终止值;``range(10)`` 生成 10 个值——长度为 10 的序列的所有合法索引。range 可以不从 0 " "开始,且可以按给定的步长递增(即使是负数步长):" #: ../../tutorial/controlflow.rst:116 msgid "" "To iterate over the indices of a sequence, you can combine :func:`range` and" " :func:`len` as follows::" msgstr "要按索引迭代序列,可以组合使用 :func:`range` 和 :func:`len`:" #: ../../tutorial/controlflow.rst:129 msgid "" "In most such cases, however, it is convenient to use the :func:`enumerate` " "function, see :ref:`tut-loopidioms`." msgstr "不过大多数情况下 :func:`enumerate` 函数很方便,详见 :ref:`tut-loopidioms`。" #: ../../tutorial/controlflow.rst:132 msgid "A strange thing happens if you just print a range::" msgstr "如果直接打印一个 range 会发生意想不到的事情:" #: ../../tutorial/controlflow.rst:137 msgid "" "In many ways the object returned by :func:`range` behaves as if it is a " "list, but in fact it isn't. 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." msgstr "" ":func:`range` " "返回的对象在很多方面和列表的行为一样,但其实它和列表不一样。该对象只有在被迭代时才一个一个地返回所期望的列表项,并没有真正生成过一个含有全部项的列表,从而节省了空间。" #: ../../tutorial/controlflow.rst:142 msgid "" "We say such an object is :term:`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 " ":keyword:`for` statement is such a construct, while an example of a function" " that takes an iterable is :func:`sum`::" msgstr "" "这种对象称为可迭代对象 :term:`iterable`,适合作为需要获取一系列值的函数或程序构件的参数。:keyword:`for` " "语句就是这样的程序构件;以可迭代对象作为参数的函数例如 :func:`sum`:" #: ../../tutorial/controlflow.rst:151 msgid "" "Later we will see more functions that return iterables and take iterables as" " arguments. Lastly, maybe you are curious about how to get a list from a " "range. Here is the solution::" msgstr "稍后我们将看到更多返回可迭代对象以及将可迭代对象作为参数的函数。 最后,也许你会很好奇如何从一个指定范围内获取一个列表。 以下是解决方案:" #: ../../tutorial/controlflow.rst:158 msgid "" "In chapter :ref:`tut-structures`, we will discuss in more detail about " ":func:`list`." msgstr "在 :ref:`tut-structures` 章节中,我们将讨论 :func:`list` 的更多细节。" #: ../../tutorial/controlflow.rst:164 msgid "" ":keyword:`!break` and :keyword:`!continue` Statements, and :keyword:`!else` " "Clauses on Loops" msgstr "循环中的 :keyword:`!break`、:keyword:`!continue` 语句及 :keyword:`!else` 子句" #: ../../tutorial/controlflow.rst:166 msgid "" "The :keyword:`break` statement, like in C, breaks out of the innermost " "enclosing :keyword:`for` or :keyword:`while` loop." msgstr "" ":keyword:`break` 语句和 C 中的类似,用于跳出最近的 :keyword:`for` 或 :keyword:`while` 循环。" #: ../../tutorial/controlflow.rst:169 msgid "" "Loop statements may have an :keyword:`!else` clause; it is executed when the" " loop terminates through exhaustion of the iterable (with :keyword:`for`) or" " when the condition becomes false (with :keyword:`while`), but not when the " "loop is terminated by a :keyword:`break` statement. This is exemplified by " "the following loop, which searches for prime numbers::" msgstr "" "循环语句支持 :keyword:`!else` 子句;:keyword:`for` 循环中,可迭代对象中的元素全部循环完毕,或 " ":keyword:`while` 循环的条件为假时,执行该子句;:keyword:`break` 语句终止循环时,不执行该子句。 " "请看下面这个查找素数的循环示例:" #: ../../tutorial/controlflow.rst:193 msgid "" "(Yes, this is the correct code. Look closely: the ``else`` clause belongs " "to the :keyword:`for` loop, **not** the :keyword:`if` statement.)" msgstr "" "(没错,这段代码就是这么写。仔细看:``else`` 子句属于 :keyword:`for` 循环,**不属于** :keyword:`if` 语句。)" #: ../../tutorial/controlflow.rst:196 msgid "" "When used with a loop, the ``else`` clause has more in common with the " "``else`` clause of a :keyword:`try` statement than it does with that of " ":keyword:`if` statements: a :keyword:`try` statement's ``else`` clause runs " "when no exception occurs, and a loop's ``else`` clause runs when no " "``break`` occurs. For more on the :keyword:`!try` statement and exceptions, " "see :ref:`tut-handling`." msgstr "" "``else`` 子句用于循环时比起 :keyword:`if` 语句的 ``else`` 子句,更像 :keyword:`try` " "语句的。:keyword:`try` 语句的 ``else`` 子句在未发生异常时执行,循环的 ``else`` 子句则在未发生 ``break`` " "时执行。 :keyword:`!try` 语句和异常详见 :ref:`tut-handling`。" #: ../../tutorial/controlflow.rst:203 msgid "" "The :keyword:`continue` statement, also borrowed from C, continues with the " "next iteration of the loop::" msgstr ":keyword:`continue` 语句,同样借鉴自 C 语言,以执行循环的下一次迭代来继续:" #: ../../tutorial/controlflow.rst:223 msgid ":keyword:`!pass` Statements" msgstr ":keyword:`!pass` 语句" #: ../../tutorial/controlflow.rst:225 msgid "" "The :keyword:`pass` statement does nothing. It can be used when a statement " "is required syntactically but the program requires no action. For example::" msgstr ":keyword:`pass` 语句不执行任何动作。语法上需要一个语句,但程序毋需执行任何动作时,可以使用该语句。例如:" #: ../../tutorial/controlflow.rst:232 msgid "This is commonly used for creating minimal classes::" msgstr "这常用于创建一个最小的类:" #: ../../tutorial/controlflow.rst:238 msgid "" "Another place :keyword:`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. The :keyword:`!pass` is silently" " ignored::" msgstr "" ":keyword:`pass` 还可用作函数或条件语句体的占位符,让你保持在更抽象的层次进行思考。:keyword:`!pass` 会被默默地忽略:" #: ../../tutorial/controlflow.rst:249 msgid "Defining Functions" msgstr "定义函数" #: ../../tutorial/controlflow.rst:251 msgid "" "We can create a function that writes the Fibonacci series to an arbitrary " "boundary::" msgstr "下列代码创建一个可以输出限定数值内的斐波那契数列函数:" #: ../../tutorial/controlflow.rst:271 msgid "" "The keyword :keyword:`def` introduces a function *definition*. 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." msgstr "*定义* 函数使用关键字 :keyword:`def`,后跟函数名与括号内的形参列表。函数语句从下一行开始,并且必须缩进。" #: ../../tutorial/controlflow.rst:276 msgid "" "The first statement of the function body can optionally be a string literal;" " this string literal is the function's documentation string, or " ":dfn:`docstring`. (More about docstrings can be found in the section " ":ref:`tut-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." msgstr "" "函数内的第一条语句是字符串时,该字符串就是文档字符串,也称为 :dfn:`docstring`,详见 :ref:`tut-" "docstrings`。利用文档字符串可以自动生成在线文档或打印版文档,还可以让开发者在浏览代码时直接查阅文档;Python " "开发者最好养成在代码中加入文档字符串的好习惯。" #: ../../tutorial/controlflow.rst:283 msgid "" "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 :keyword:`global` statement, or, " "for variables of enclosing functions, named in a :keyword:`nonlocal` " "statement), although they may be referenced." msgstr "" "函数在 *执行* " "时使用函数局部变量符号表,所有函数变量赋值都存在局部符号表中;引用变量时,首先,在局部符号表里查找变量,然后,是外层函数局部符号表,再是全局符号表,最后是内置名称符号表。因此,尽管可以引用全局变量和外层函数的变量,但最好不要在函数内直接赋值(除非是" " :keyword:`global` 语句定义的全局变量,或 :keyword:`nonlocal` 语句定义的外层函数变量)。" #: ../../tutorial/controlflow.rst:294 msgid "" "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). [#]_ When a function calls " "another function, or calls itself recursively, a new local symbol table is " "created for that call." msgstr "" "在调用函数时会将实际参数(实参)引入到被调用函数的局部符号表中;因此,实参是使用 *按值调用* 来传递的(其中的 *值* 始终是对象的 *引用* " "而不是对象的值)。 [#]_ 当一个函数调用另外一个函数时,会为该调用创建一个新的局部符号表。" #: ../../tutorial/controlflow.rst:301 msgid "" "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::" msgstr "" "函数定义在当前符号表中把函数名与函数对象关联在一起。解释器把函数名指向的对象作为用户自定义函数。还可以使用其他名称指向同一个函数对象,并访问访该函数:" #: ../../tutorial/controlflow.rst:312 msgid "" "Coming from other languages, you might object that ``fib`` is not a function" " but a procedure since it doesn't return a value. In fact, even functions " "without a :keyword:`return` statement do return a value, albeit a rather " "boring one. This value is called ``None`` (it's a built-in name). Writing " "the value ``None`` is normally suppressed by the interpreter if it would be " "the only value written. You can see it if you really want to using " ":func:`print`::" msgstr "" "如果你用过其他语言,你可能会认为 ``fib`` 不是函数而是一个过程,因为它没有返回值。 事实上,即使没有 :keyword:`return` " "语句的函数也有返回值,尽管这个值可能相当无聊。 这个值被称为 ``None`` (是一个内置名称)。 通常解释器会屏蔽单独的返回值 ``None``。 " "如果你确有需要可以使用 :func:`print` 查看它::" #: ../../tutorial/controlflow.rst:323 msgid "" "It is simple to write a function that returns a list of the numbers of the " "Fibonacci series, instead of printing it::" msgstr "编写不直接输出斐波那契数列运算结果,而是返回运算结果列表的函数也非常简单:" #: ../../tutorial/controlflow.rst:339 msgid "This example, as usual, demonstrates some new Python features:" msgstr "本例也新引入了一些 Python 功能:" #: ../../tutorial/controlflow.rst:341 msgid "" "The :keyword:`return` statement returns with a value from a function. " ":keyword:`!return` without an expression argument returns ``None``. Falling " "off the end of a function also returns ``None``." msgstr "" ":keyword:`return` 语句返回函数的值。:keyword:`!return` 语句不带表达式参数时,返回 " "``None``。函数执行完毕退出也返回 ``None``。" #: ../../tutorial/controlflow.rst:345 msgid "" "The statement ``result.append(a)`` calls a *method* of the list object " "``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. 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 " ":ref:`tut-classes`) The method :meth:`append` 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 ``result = result + [a]``, but more " "efficient." msgstr "" "``result.append(a)`` 语句调用了列表对象 ``result`` 的 *方法* 。方法是“从属于”对象的函数,命名为 " "``obj.methodname``,``obj`` 是对象(也可以是表达式),``methodname`` " "是对象类型定义的方法名。不同类型定义不同的方法,不同类型的方法名可以相同,且不会引起歧义。(用 *类* 可以自定义对象类型和方法,详见 " ":ref:`tut-classes` )示例中的方法 :meth:`append` 是为列表对象定义的,用于在列表末尾添加新元素。本例中,该方法相当于 " "``result = result + [a]`` ,但更有效。" #: ../../tutorial/controlflow.rst:360 msgid "More on Defining Functions" msgstr "函数定义详解" #: ../../tutorial/controlflow.rst:362 msgid "" "It is also possible to define functions with a variable number of arguments." " There are three forms, which can be combined." msgstr "函数定义支持可变数量的参数。这里列出三种可以组合使用的形式。" #: ../../tutorial/controlflow.rst:369 msgid "Default Argument Values" msgstr "默认值参数" #: ../../tutorial/controlflow.rst:371 msgid "" "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::" msgstr "为参数指定默认值是非常有用的方式。调用函数时,可以使用比定义时更少的参数,例如:" #: ../../tutorial/controlflow.rst:387 msgid "This function can be called in several ways:" msgstr "该函数可以用以下方式调用:" #: ../../tutorial/controlflow.rst:389 msgid "" "giving only the mandatory argument: ``ask_ok('Do you really want to " "quit?')``" msgstr "只给出必选实参:``ask_ok('Do you really want to quit?')``" #: ../../tutorial/controlflow.rst:391 msgid "" "giving one of the optional arguments: ``ask_ok('OK to overwrite the file?', " "2)``" msgstr "给出一个可选实参:``ask_ok('OK to overwrite the file?', 2)``" #: ../../tutorial/controlflow.rst:393 msgid "" "or even giving all arguments: ``ask_ok('OK to overwrite the file?', 2, 'Come" " on, only yes or no!')``" msgstr "" "给出所有实参:``ask_ok('OK to overwrite the file?', 2, 'Come on, only yes or " "no!')``" #: ../../tutorial/controlflow.rst:396 msgid "" "This example also introduces the :keyword:`in` keyword. This tests whether " "or not a sequence contains a certain value." msgstr "本例还使用了关键字 :keyword:`in` ,用于确认序列中是否包含某个值。" #: ../../tutorial/controlflow.rst:399 msgid "" "The default values are evaluated at the point of function definition in the " "*defining* scope, so that ::" msgstr "默认值在 *定义* 作用域里的函数定义中求值,所以:" #: ../../tutorial/controlflow.rst:410 msgid "will print ``5``." msgstr "上例输出的是 ``5``。" #: ../../tutorial/controlflow.rst:412 msgid "" "**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::" msgstr "" "**重要警告:** 默认值只计算一次。默认值为列表、字典或类实例等可变对象时,会产生与该规则不同的结果。例如,下面的函数会累积后续调用时传递的参数:" #: ../../tutorial/controlflow.rst:425 msgid "This will print ::" msgstr "输出结果如下:" #: ../../tutorial/controlflow.rst:431 msgid "" "If you don't want the default to be shared between subsequent calls, you can" " write the function like this instead::" msgstr "不想在后续调用之间共享默认值时,应以如下方式编写函数:" #: ../../tutorial/controlflow.rst:444 msgid "Keyword Arguments" msgstr "关键字参数" #: ../../tutorial/controlflow.rst:446 msgid "" "Functions can also be called using :term:`keyword arguments ` of the form ``kwarg=value``. For instance, the following " "function::" msgstr "" "``kwarg=value`` 形式的 :term:`关键字参数 ` 也可以用于调用函数。函数示例如下:" #: ../../tutorial/controlflow.rst:455 msgid "" "accepts one required argument (``voltage``) and three optional arguments " "(``state``, ``action``, and ``type``). This function can be called in any " "of the following ways::" msgstr "" "该函数接受一个必选参数(``voltage``)和三个可选参数(``state``, ``action`` 和 " "``type``)。该函数可用下列方式调用:" #: ../../tutorial/controlflow.rst:466 msgid "but all the following calls would be invalid::" msgstr "以下调用函数的方式都无效:" #: ../../tutorial/controlflow.rst:473 msgid "" "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. This also includes non-" "optional arguments (e.g. ``parrot(voltage=1000)`` is valid too). No argument" " may receive a value more than once. Here's an example that fails due to " "this restriction::" msgstr "" "函数调用时,关键字参数必须跟在位置参数后面。所有传递的关键字参数都必须匹配一个函数接受的参数(比如,``actor`` 不是函数 ``parrot`` " "的有效参数),关键字参数的顺序并不重要。这也包括必选参数,(比如,``parrot(voltage=1000)`` " "也有效)。不能对同一个参数多次赋值,下面就是一个因此限制而失败的例子:" #: ../../tutorial/controlflow.rst:489 msgid "" "When a final formal parameter of the form ``**name`` is present, it receives" " a dictionary (see :ref:`typesmapping`) containing all keyword arguments " "except for those corresponding to a formal parameter. This may be combined " "with a formal parameter of the form ``*name`` (described in the next " "subsection) which receives a :ref:`tuple ` containing the " "positional arguments beyond the formal parameter list. (``*name`` must " "occur before ``**name``.) For example, if we define a function like this::" msgstr "" "最后一个形参为 ``**name`` 形式时,接收一个字典(详见 " ":ref:`typesmapping`),该字典包含与函数中已定义形参对应之外的所有关键字参数。``**name`` 形参可以与 ``*name`` " "形参(下一小节介绍)组合使用(``*name`` 必须在 ``**name`` 前面), ``*name`` 形参接收一个 :ref:`元组 `,该元组包含形参列表之外的位置参数。例如,可以定义下面这样的函数:" #: ../../tutorial/controlflow.rst:506 msgid "It could be called like this::" msgstr "该函数可以用如下方式调用:" #: ../../tutorial/controlflow.rst:514 msgid "and of course it would print:" msgstr "输出结果如下:" #: ../../tutorial/controlflow.rst:527 msgid "" "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." msgstr "注意,关键字参数在输出结果中的顺序与调用函数时的顺序一致。" #: ../../tutorial/controlflow.rst:531 msgid "Special parameters" msgstr "特殊参数" #: ../../tutorial/controlflow.rst:533 msgid "" "By default, arguments may be passed to a Python function either by position " "or explicitly by keyword. 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." msgstr "" "默认情况下,参数可以按位置或显式关键字传递给 Python " "函数。为了让代码易读、高效,最好限制参数的传递方式,这样,开发者只需查看函数定义,即可确定参数项是仅按位置、按位置或关键字,还是仅按关键字传递。" #: ../../tutorial/controlflow.rst:539 msgid "A function definition may look like:" msgstr "函数定义如下:" #: ../../tutorial/controlflow.rst:550 msgid "" "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." msgstr "``/`` 和 ``*`` 是可选的。这些符号表明形参如何把参数值传递给函数:位置、位置或关键字、关键字。关键字形参也叫作命名形参。" #: ../../tutorial/controlflow.rst:557 msgid "Positional-or-Keyword Arguments" msgstr "位置或关键字参数" #: ../../tutorial/controlflow.rst:559 msgid "" "If ``/`` and ``*`` are not present in the function definition, arguments may" " be passed to a function by position or by keyword." msgstr "函数定义中未使用 ``/`` 和 ``*`` 时,参数可以按位置或关键字传递给函数。" #: ../../tutorial/controlflow.rst:564 msgid "Positional-Only Parameters" msgstr "仅位置参数" #: ../../tutorial/controlflow.rst:566 msgid "" "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." msgstr "" "此处再介绍一些细节,特定形参可以标记为 *仅限位置*。*仅限位置* 时,形参的顺序很重要,且这些形参不能用关键字传递。仅限位置形参应放在 ``/`` " "(正斜杠)前。``/`` 用于在逻辑上分割仅限位置形参与其它形参。如果函数定义中没有 ``/``,则表示没有仅限位置形参。" #: ../../tutorial/controlflow.rst:574 msgid "" "Parameters following the ``/`` may be *positional-or-keyword* or *keyword-" "only*." msgstr "``/`` 后可以是 *位置或关键字* 或 *仅限关键字* 形参。" #: ../../tutorial/controlflow.rst:578 msgid "Keyword-Only Arguments" msgstr "仅限关键字参数" #: ../../tutorial/controlflow.rst:580 msgid "" "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." msgstr "把形参标记为 *仅限关键字*,表明必须以关键字参数形式传递该形参,应在参数列表中第一个 *仅限关键字* 形参前添加 ``*``。" #: ../../tutorial/controlflow.rst:586 msgid "Function Examples" msgstr "函数示例" #: ../../tutorial/controlflow.rst:588 msgid "" "Consider the following example function definitions paying close attention " "to the markers ``/`` and ``*``::" msgstr "请看下面的函数定义示例,注意 ``/`` 和 ``*`` 标记:" #: ../../tutorial/controlflow.rst:604 msgid "" "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::" msgstr "第一个函数定义 ``standard_arg`` 是最常见的形式,对调用方式没有任何限制,可以按位置也可以按关键字传递参数:" #: ../../tutorial/controlflow.rst:614 msgid "" "The second function ``pos_only_arg`` is restricted to only use positional " "parameters as there is a ``/`` in the function definition::" msgstr "第二个函数 ``pos_only_arg`` 的函数定义中有 ``/``,仅限使用位置形参:" #: ../../tutorial/controlflow.rst:625 msgid "" "The third function ``kwd_only_args`` only allows keyword arguments as " "indicated by a ``*`` in the function definition::" msgstr "第三个函数 ``kwd_only_args`` 的函数定义通过 ``*`` 表明仅限关键字参数:" #: ../../tutorial/controlflow.rst:636 msgid "" "And the last uses all three calling conventions in the same function " "definition::" msgstr "最后一个函数在同一个函数定义中,使用了全部三种调用惯例:" #: ../../tutorial/controlflow.rst:656 msgid "" "Finally, consider this function definition which has a potential collision " "between the positional argument ``name`` and ``**kwds`` which has ``name`` " "as a key::" msgstr "下面的函数定义中,``kwds`` 把 ``name`` 当作键,因此,可能与位置参数 ``name`` 产生潜在冲突:" #: ../../tutorial/controlflow.rst:661 msgid "" "There is no possible call that will make it return ``True`` as the keyword " "``'name'`` will always bind to the first parameter. For example::" msgstr "调用该函数不可能返回 ``True``,因为关键字 ``'name'`` 总与第一个形参绑定。例如:" #: ../../tutorial/controlflow.rst:670 msgid "" "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::" msgstr "" "加上 ``/`` (仅限位置参数)后,就可以了。此时,函数定义把 ``name`` 当作位置参数,``'name'`` 也可以作为关键字参数的键:" #: ../../tutorial/controlflow.rst:677 msgid "" "In other words, the names of positional-only parameters can be used in " "``**kwds`` without ambiguity." msgstr "换句话说,仅限位置形参的名称可以在 ``**kwds`` 中使用,而不产生歧义。" #: ../../tutorial/controlflow.rst:682 msgid "Recap" msgstr "小结" #: ../../tutorial/controlflow.rst:684 msgid "" "The use case will determine which parameters to use in the function " "definition::" msgstr "以下用例决定哪些形参可以用于函数定义:" #: ../../tutorial/controlflow.rst:688 msgid "As guidance:" msgstr "说明:" #: ../../tutorial/controlflow.rst:690 msgid "" "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." msgstr "使用仅限位置形参,可以让用户无法使用形参名。形参名没有实际意义时,强制调用函数的实参顺序时,或同时接收位置形参和关键字时,这种方式很有用。" #: ../../tutorial/controlflow.rst:695 msgid "" "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." msgstr "当形参名有实际意义,且显式名称可以让函数定义更易理解时,阻止用户依赖传递实参的位置时,才使用关键字。" #: ../../tutorial/controlflow.rst:698 msgid "" "For an API, use positional-only to prevent breaking API changes if the " "parameter's name is modified in the future." msgstr "对于 API,使用仅限位置形参,可以防止未来修改形参名时造成破坏性的 API 变动。" #: ../../tutorial/controlflow.rst:704 msgid "Arbitrary Argument Lists" msgstr "任意实参列表" #: ../../tutorial/controlflow.rst:709 msgid "" "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 :ref:`tut-tuples`). Before the variable number " "of arguments, zero or more normal arguments may occur. ::" msgstr "" "调用函数时,使用任意数量的实参是最少见的选项。这些实参包含在元组中(详见 :ref:`tut-tuples` " ")。在可变数量的实参之前,可能有若干个普通参数:" #: ../../tutorial/controlflow.rst:718 msgid "" "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. ::" msgstr "" "一般来说,这些 ``可变参数`` 将在形式参数列表的末尾,因为它们收集传递给函数的所有剩余输入参数。出现在 ``*args`` " "参数之后的任何形式参数都是 ‘仅限关键字参数’,也就是说它们只能作为关键字参数而不能是位置参数。::" #: ../../tutorial/controlflow.rst:735 msgid "Unpacking Argument Lists" msgstr "解包实参列表" #: ../../tutorial/controlflow.rst:737 msgid "" "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 :func:`range` function " "expects separate *start* and *stop* arguments. If they are not available " "separately, write the function call with the ``*``\\ -operator to unpack " "the arguments out of a list or tuple::" msgstr "" "函数调用要求独立的位置参数,但实参在列表或元组里时,要执行相反的操作。例如,内置的 :func:`range` 函数要求独立的 *start* 和 " "*stop* 实参。如果这些参数不是独立的,则要在调用函数时,用 ``*`` 操作符把实参从列表或元组解包出来:" #: ../../tutorial/controlflow.rst:753 msgid "" "In the same fashion, dictionaries can deliver keyword arguments with the " "``**``\\ -operator::" msgstr "同样,字典可以用 ``**`` 操作符传递关键字参数:" #: ../../tutorial/controlflow.rst:769 msgid "Lambda Expressions" msgstr "Lambda 表达式" #: ../../tutorial/controlflow.rst:771 msgid "" "Small anonymous functions can be created with the :keyword:`lambda` keyword." " This function returns the sum of its two arguments: ``lambda a, b: a+b``. " "Lambda functions can be used wherever function objects are required. 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::" msgstr "" ":keyword:`lambda` 关键字用于创建小巧的匿名函数。``lambda a, b: a+b`` 函数返回两个参数的和。Lambda " "函数可用于任何需要函数对象的地方。在语法上,匿名函数只能是单个表达式。在语义上,它只是常规函数定义的语法糖。与嵌套函数定义一样,lambda " "函数可以引用包含作用域中的变量:" #: ../../tutorial/controlflow.rst:788 msgid "" "The above example uses a lambda expression to return a function. Another " "use is to pass a small function as an argument::" msgstr "上例用 lambda 表达式返回函数。还可以把匿名函数用作传递的实参:" #: ../../tutorial/controlflow.rst:800 msgid "Documentation Strings" msgstr "文档字符串" #: ../../tutorial/controlflow.rst:807 msgid "" "Here are some conventions about the content and formatting of documentation " "strings." msgstr "以下是文档字符串内容和格式的约定。" #: ../../tutorial/controlflow.rst:810 msgid "" "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." msgstr "" "第一行应为对象用途的简短摘要。为保持简洁,不要在这里显式说明对象名或类型,因为可通过其他方式获取这些信息(除非该名称碰巧是描述函数操作的动词)。这一行应以大写字母开头,以句点结尾。" #: ../../tutorial/controlflow.rst:816 msgid "" "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." msgstr "文档字符串为多行时,第二行应为空白行,在视觉上将摘要与其余描述分开。后面的行可包含若干段落,描述对象的调用约定、副作用等。" #: ../../tutorial/controlflow.rst:821 msgid "" "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. 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)." msgstr "" "Python 解析器不会删除 Python 中多行字符串字面值的缩进,因此,文档处理工具应在必要时删除缩进。这项操作遵循以下约定:文档字符串第一行 " "*之后* " "的第一个非空行决定了整个文档字符串的缩进量(第一行通常与字符串开头的引号相邻,其缩进在字符串中并不明显,因此,不能用第一行的缩进),然后,删除字符串中所有行开头处与此缩进“等价”的空白符。不能有比此缩进更少的行,但如果出现了缩进更少的行,应删除这些行的所有前导空白符。转化制表符后(通常为" " 8 个空格),应测试空白符的等效性。" #: ../../tutorial/controlflow.rst:833 msgid "Here is an example of a multi-line docstring::" msgstr "下面是多行文档字符串的一个例子:" #: ../../tutorial/controlflow.rst:851 msgid "Function Annotations" msgstr "函数注解" #: ../../tutorial/controlflow.rst:859 msgid "" ":ref:`Function annotations ` are completely optional metadata " "information about the types used by user-defined functions (see :pep:`3107` " "and :pep:`484` for more information)." msgstr "" ":ref:`函数注解 ` 是可选的用户自定义函数类型的元数据完整信息(详见 :pep:`3107` 和 :pep:`484` )。" #: ../../tutorial/controlflow.rst:863 msgid "" ":term:`Annotations ` are stored in the " ":attr:`__annotations__` attribute of the function as a dictionary and have " "no effect on any other part of the function. 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 :keyword:`def` statement. The " "following example has a required argument, an optional argument, and the " "return value annotated::" msgstr "" ":term:`标注 ` 以字典的形式存放在函数的 :attr:`__annotations__` " "属性中,并且不会影响函数的任何其他部分。 形参标注的定义方式是在形参名后加冒号,后面跟一个表达式,该表达式会被求值为标注的值。 " "返回值标注的定义方式是加组合符号 ``->``,后面跟一个表达式,该标注位于形参列表和表示 :keyword:`def` 语句结束的冒号之间。 " "下面的示例有一个必须的参数,一个可选的关键字参数以及返回值都带有相应的标注::" #: ../../tutorial/controlflow.rst:885 msgid "Intermezzo: Coding Style" msgstr "小插曲:编码风格" #: ../../tutorial/controlflow.rst:890 msgid "" "Now that you are about to write longer, more complex pieces of Python, it is" " a good time to talk about *coding style*. 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." msgstr "" "现在你将要写更长,更复杂的 Python 代码,是时候讨论一下 *代码风格* 了。 " "大多数语言都能以不同的风格被编写(或更准确地说,被格式化);有些比其他的更具有可读性。 " "能让其他人轻松阅读你的代码总是一个好主意,采用一种好的编码风格对此有很大帮助。" #: ../../tutorial/controlflow.rst:896 msgid "" "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. Every" " Python developer should read it at some point; here are the most important " "points extracted for you:" msgstr "" "Python 项目大多都遵循 :pep:`8` 的风格指南;它推行的编码风格易于阅读、赏心悦目。Python " "开发者均应抽时间悉心研读;以下是该提案中的核心要点:" #: ../../tutorial/controlflow.rst:901 msgid "Use 4-space indentation, and no tabs." msgstr "缩进,用 4 个空格,不要用制表符。" #: ../../tutorial/controlflow.rst:903 msgid "" "4 spaces are a good compromise between small indentation (allows greater " "nesting depth) and large indentation (easier to read). Tabs introduce " "confusion, and are best left out." msgstr "4 个空格是小缩进(更深嵌套)和大缩进(更易阅读)之间的折中方案。制表符会引起混乱,最好别用。" #: ../../tutorial/controlflow.rst:907 msgid "Wrap lines so that they don't exceed 79 characters." msgstr "换行,一行不超过 79 个字符。" #: ../../tutorial/controlflow.rst:909 msgid "" "This helps users with small displays and makes it possible to have several " "code files side-by-side on larger displays." msgstr "这样换行的小屏阅读体验更好,还便于在大屏显示器上并排阅读多个代码文件。" #: ../../tutorial/controlflow.rst:912 msgid "" "Use blank lines to separate functions and classes, and larger blocks of code" " inside functions." msgstr "用空行分隔函数和类,及函数内较大的代码块。" #: ../../tutorial/controlflow.rst:915 msgid "When possible, put comments on a line of their own." msgstr "最好把注释放到单独一行。" #: ../../tutorial/controlflow.rst:917 msgid "Use docstrings." msgstr "使用文档字符串。" #: ../../tutorial/controlflow.rst:919 msgid "" "Use spaces around operators and after commas, but not directly inside " "bracketing constructs: ``a = f(1, 2) + g(3, 4)``." msgstr "运算符前后、逗号后要用空格,但不要直接在括号内使用: ``a = f(1, 2) + g(3, 4)``。" #: ../../tutorial/controlflow.rst:922 msgid "" "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 :ref:`tut-firstclasses` for more on classes and methods)." msgstr "" "类和函数的命名要一致;按惯例,命名类用 ``UpperCamelCase``,命名函数与方法用 " "``lowercase_with_underscores``。命名方法中第一个参数总是用 ``self`` (类和方法详见 :ref:`tut-" "firstclasses`)。" #: ../../tutorial/controlflow.rst:927 msgid "" "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." msgstr "编写用于国际多语环境的代码时,不要用生僻的编码。Python 默认的 UTF-8 或纯 ASCII 可以胜任各种情况。" #: ../../tutorial/controlflow.rst:931 msgid "" "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." msgstr "同理,就算多语阅读、维护代码的可能再小,也不要在标识符中使用非 ASCII 字符。" #: ../../tutorial/controlflow.rst:937 msgid "Footnotes" msgstr "备注" #: ../../tutorial/controlflow.rst:938 msgid "" "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)." msgstr "实际上,*对象引用调用* 这种说法更好,因为,传递的是可变对象时,调用者能发现被调者做出的任何更改(插入列表的元素)。"