# SOME DESCRIPTIVE TITLE. # Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: # Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.12\n" "Report-Msgid-Bugs-To: \n" "POT-Creation-Date: 2025-07-25 16:03+0000\n" "PO-Revision-Date: 2025-07-18 19:59+0000\n" "Last-Translator: Rafael Fontenelle , 2025\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 "" "As well as the :keyword:`while` statement just introduced, Python uses a few" " more that we will encounter in this chapter." 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:19 msgid "" ">>> x = int(input(\"Please enter an integer: \"))\n" "Please enter an integer: 42\n" ">>> if x < 0:\n" "... x = 0\n" "... print('Negative changed to zero')\n" "... elif x == 0:\n" "... print('Zero')\n" "... elif x == 1:\n" "... print('Single')\n" "... else:\n" "... print('More')\n" "...\n" "More" msgstr "" ">>> x = int(input(\"Please enter an integer: \"))\n" "Please enter an integer: 42\n" ">>> if x < 0:\n" "... x = 0\n" "... print('Negative changed to zero')\n" "... elif x == 0:\n" "... print('Zero')\n" "... elif x == 1:\n" "... print('Single')\n" "... else:\n" "... print('More')\n" "...\n" "更多" #: ../../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:39 msgid "" "If you're comparing the same value to several constants, or checking for " "specific types or attributes, you may also find the :keyword:`!match` " "statement useful. For more details see :ref:`tut-match`." msgstr "" "如果是把一个值与多个常量进行比较,或者检查特定类型或属性,:keyword:`!match` 语句更有用。详见 :ref:`tut-match`。" #: ../../tutorial/controlflow.rst:46 msgid ":keyword:`!for` Statements" msgstr ":keyword:`!for` 语句" #: ../../tutorial/controlflow.rst:51 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:63 msgid "" ">>> # Measure some strings:\n" ">>> words = ['cat', 'window', 'defenestrate']\n" ">>> for w in words:\n" "... print(w, len(w))\n" "...\n" "cat 3\n" "window 6\n" "defenestrate 12" msgstr "" ">>> # 度量一些字符串:\n" ">>> words = ['cat', 'window', 'defenestrate']\n" ">>> for w in words:\n" "... print(w, len(w))\n" "...\n" "cat 3\n" "window 6\n" "defenestrate 12" #: ../../tutorial/controlflow.rst:72 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:76 msgid "" "# Create a sample collection\n" "users = {'Hans': 'active', 'Éléonore': 'inactive', '景太郎': 'active'}\n" "\n" "# Strategy: Iterate over a copy\n" "for user, status in users.copy().items():\n" " if status == 'inactive':\n" " del users[user]\n" "\n" "# Strategy: Create a new collection\n" "active_users = {}\n" "for user, status in users.items():\n" " if status == 'active':\n" " active_users[user] = status" msgstr "" "# 创建示例多项集\n" "users = {'Hans': 'active', 'Éléonore': 'inactive', '景太郎': 'active'}\n" "\n" "# 策略:迭代一个副本\n" "for user, status in users.copy().items():\n" " if status == 'inactive':\n" " del users[user]\n" "\n" "# 策略:创建一个新多项集\n" "active_users = {}\n" "for user, status in users.items():\n" " if status == 'active':\n" " active_users[user] = status" #: ../../tutorial/controlflow.rst:94 msgid "The :func:`range` Function" msgstr ":func:`range` 函数" #: ../../tutorial/controlflow.rst:96 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:99 msgid "" ">>> for i in range(5):\n" "... print(i)\n" "...\n" "0\n" "1\n" "2\n" "3\n" "4" msgstr "" ">>> for i in range(5):\n" "... print(i)\n" "...\n" "0\n" "1\n" "2\n" "3\n" "4" #: ../../tutorial/controlflow.rst:108 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:113 msgid "" ">>> list(range(5, 10))\n" "[5, 6, 7, 8, 9]\n" "\n" ">>> list(range(0, 10, 3))\n" "[0, 3, 6, 9]\n" "\n" ">>> list(range(-10, -100, -30))\n" "[-10, -40, -70]" msgstr "" ">>> list(range(5, 10))\n" "[5, 6, 7, 8, 9]\n" "\n" ">>> list(range(0, 10, 3))\n" "[0, 3, 6, 9]\n" "\n" ">>> list(range(-10, -100, -30))\n" "[-10, -40, -70]" #: ../../tutorial/controlflow.rst:122 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:125 msgid "" ">>> a = ['Mary', 'had', 'a', 'little', 'lamb']\n" ">>> for i in range(len(a)):\n" "... print(i, a[i])\n" "...\n" "0 Mary\n" "1 had\n" "2 a\n" "3 little\n" "4 lamb" msgstr "" ">>> a = ['Mary', 'had', 'a', 'little', 'lamb']\n" ">>> for i in range(len(a)):\n" "... print(i, a[i])\n" "...\n" "0 Mary\n" "1 had\n" "2 a\n" "3 little\n" "4 lamb" #: ../../tutorial/controlflow.rst:135 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:138 msgid "A strange thing happens if you just print a range::" msgstr "如果直接打印一个 range 会发生意想不到的事情:" #: ../../tutorial/controlflow.rst:140 msgid "" ">>> range(10)\n" "range(0, 10)" msgstr "" ">>> range(10)\n" "range(0, 10)" #: ../../tutorial/controlflow.rst:143 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:148 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:154 msgid "" ">>> sum(range(4)) # 0 + 1 + 2 + 3\n" "6" msgstr "" ">>> sum(range(4)) # 0 + 1 + 2 + 3\n" "6" #: ../../tutorial/controlflow.rst:157 msgid "" "Later we will see more functions that return iterables and take iterables as" " arguments. 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" msgstr ":keyword:`!break` 和 :keyword:`!continue` 语句" #: ../../tutorial/controlflow.rst:166 msgid "" "The :keyword:`break` statement breaks out of the innermost enclosing " ":keyword:`for` or :keyword:`while` loop::" msgstr ":keyword:`break` 语句将跳出最近的一层 :keyword:`for` 或 :keyword:`while` 循环::" #: ../../tutorial/controlflow.rst:169 msgid "" ">>> for n in range(2, 10):\n" "... for x in range(2, n):\n" "... if n % x == 0:\n" "... print(f\"{n} equals {x} * {n//x}\")\n" "... break\n" "...\n" "4 equals 2 * 2\n" "6 equals 2 * 3\n" "8 equals 2 * 4\n" "9 equals 3 * 3" msgstr "" ">>> for n in range(2, 10):\n" "... for x in range(2, n):\n" "... if n % x == 0:\n" "... print(f\"{n} equals {x} * {n//x}\")\n" "... break\n" "...\n" "4 equals 2 * 2\n" "6 equals 2 * 3\n" "8 equals 2 * 4\n" "9 equals 3 * 3" #: ../../tutorial/controlflow.rst:180 msgid "" "The :keyword:`continue` statement continues with the next iteration of the " "loop::" msgstr ":keyword:`continue` 语句将继续执行循环的下一次迭代::" #: ../../tutorial/controlflow.rst:183 msgid "" ">>> for num in range(2, 10):\n" "... if num % 2 == 0:\n" "... print(f\"Found an even number {num}\")\n" "... continue\n" "... print(f\"Found an odd number {num}\")\n" "...\n" "Found an even number 2\n" "Found an odd number 3\n" "Found an even number 4\n" "Found an odd number 5\n" "Found an even number 6\n" "Found an odd number 7\n" "Found an even number 8\n" "Found an odd number 9" msgstr "" ">>> for num in range(2, 10):\n" "... if num % 2 == 0:\n" "... print(f\"Found an even number {num}\")\n" "... continue\n" "... print(f\"Found an odd number {num}\")\n" "...\n" "Found an even number 2\n" "Found an odd number 3\n" "Found an even number 4\n" "Found an odd number 5\n" "Found an even number 6\n" "Found an odd number 7\n" "Found an even number 8\n" "Found an odd number 9" #: ../../tutorial/controlflow.rst:202 msgid ":keyword:`!else` Clauses on Loops" msgstr "循环的 :keyword:`!else` 子句" #: ../../tutorial/controlflow.rst:204 msgid "" "In a :keyword:`!for` or :keyword:`!while` loop the :keyword:`!break` " "statement may be paired with an :keyword:`!else` clause. If the loop " "finishes without executing the :keyword:`!break`, the :keyword:`!else` " "clause executes." msgstr "" "在 :keyword:`!for` 或 :keyword:`!while` 循环中 :keyword:`!break` 语句可能对应一个 " ":keyword:`!else` 子句。 如果循环在未执行 :keyword:`!break` 的情况下结束,:keyword:`!else` " "子句将会执行。" #: ../../tutorial/controlflow.rst:208 msgid "" "In a :keyword:`for` loop, the :keyword:`!else` clause is executed after the " "loop finishes its final iteration, that is, if no break occurred." msgstr "" "在 :keyword:`for` 循环中,:keyword:`!else` 子句会在循环结束其他最后一次迭代之后,即未执行 break 的情况下被执行。" #: ../../tutorial/controlflow.rst:211 msgid "" "In a :keyword:`while` loop, it's executed after the loop's condition becomes" " false." msgstr "在 :keyword:`while` 循环中,它会在循环条件变为假值后执行。" #: ../../tutorial/controlflow.rst:213 msgid "" "In either kind of loop, the :keyword:`!else` clause is **not** executed if " "the loop was terminated by a :keyword:`break`. Of course, other ways of " "ending the loop early, such as a :keyword:`return` or a raised exception, " "will also skip execution of the :keyword:`else` clause." msgstr "" "在这两类循环中,当在循环被 :keyword:`break` 终结时 :keyword:`!else` 子句 **不会** 被执行。 " "当然,其他提前结束循环的方式,如 :keyword:`return` 或是引发异常,也会跳过 :keyword:`else` 子句的执行。" #: ../../tutorial/controlflow.rst:218 msgid "" "This is exemplified in the following :keyword:`!for` loop, which searches " "for prime numbers::" msgstr "下面的搜索质数的 :keyword:`!for` 循环就是一个例子:" #: ../../tutorial/controlflow.rst:221 msgid "" ">>> for n in range(2, 10):\n" "... for x in range(2, n):\n" "... if n % x == 0:\n" "... print(n, 'equals', x, '*', n//x)\n" "... break\n" "... else:\n" "... # loop fell through without finding a factor\n" "... print(n, 'is a prime number')\n" "...\n" "2 is a prime number\n" "3 is a prime number\n" "4 equals 2 * 2\n" "5 is a prime number\n" "6 equals 2 * 3\n" "7 is a prime number\n" "8 equals 2 * 4\n" "9 equals 3 * 3" msgstr "" ">>> for n in range(2, 10):\n" "... for x in range(2, n):\n" "... if n % x == 0:\n" "... print(n, 'equals', x, '*', n//x)\n" "... break\n" "... else:\n" "... # 循环到底未找到一个因数\n" "... print(n, 'is a prime number')\n" "...\n" "2 is a prime number\n" "3 is a prime number\n" "4 equals 2 * 2\n" "5 is a prime number\n" "6 equals 2 * 3\n" "7 is a prime number\n" "8 equals 2 * 4\n" "9 equals 3 * 3" #: ../../tutorial/controlflow.rst:239 msgid "" "(Yes, this is the correct code. Look closely: the ``else`` clause belongs " "to the ``for`` loop, **not** the ``if`` statement.)" msgstr "(对,这是正确的代码。 仔细看:其中 ``else`` 子句属于 ``for`` 循环,而 **不属于** ``if`` 语句。)" #: ../../tutorial/controlflow.rst:242 msgid "" "One way to think of the else clause is to imagine it paired with the ``if`` " "inside the loop. As the loop executes, it will run a sequence like " "if/if/if/else. The ``if`` is inside the loop, encountered a number of times." " If the condition is ever true, a ``break`` will happen. If the condition is" " never true, the ``else`` clause outside the loop will execute." msgstr "" "分析 else 子句的一种方式是想象它对应于循环内的 ``if``。 当循环执行时,它将运行一系列的 if/if/if/else。 ``if`` " "位于循环内部,会出现多次。 当出现条件为真的情况时,将发生 ``break``。 如果条件一直不为真,则循环外的 ``else`` 子句将被执行。" #: ../../tutorial/controlflow.rst:248 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 " "``if`` statements: a ``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 ``try`` statement and exceptions, see :ref:`tut-" "handling`." msgstr "" "当配合循环使用时,``else`` 子句更像是 :keyword:`try` 语句的 ``else`` 子句而不像 ``if`` 语句的相应子句:一个 " "``try`` 语句的 ``else`` 子句会在未发生异常时运行,而一个循环的 ``else`` 子句会在未发生 ``break`` 时运行。 有关 " "``try`` 语句和异常的详情,请参阅 :ref:`tut-handling`。" #: ../../tutorial/controlflow.rst:257 msgid ":keyword:`!pass` Statements" msgstr ":keyword:`!pass` 语句" #: ../../tutorial/controlflow.rst:259 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:262 msgid "" ">>> while True:\n" "... pass # Busy-wait for keyboard interrupt (Ctrl+C)\n" "..." msgstr "" ">>> while True:\n" "... pass # 无限等待键盘中断 (Ctrl+C)\n" "..." #: ../../tutorial/controlflow.rst:266 msgid "This is commonly used for creating minimal classes::" msgstr "这常用于创建一个最小的类:" #: ../../tutorial/controlflow.rst:268 msgid "" ">>> class MyEmptyClass:\n" "... pass\n" "..." msgstr "" ">>> class MyEmptyClass:\n" "... pass\n" "..." #: ../../tutorial/controlflow.rst:272 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:276 msgid "" ">>> def initlog(*args):\n" "... pass # Remember to implement this!\n" "..." msgstr "" ">>> def initlog(*args):\n" "... pass # 记得实现这个!\n" "..." #: ../../tutorial/controlflow.rst:284 msgid ":keyword:`!match` Statements" msgstr ":keyword:`!match` 语句" #: ../../tutorial/controlflow.rst:286 msgid "" "A :keyword:`match` statement takes an expression and compares its value to " "successive patterns given as one or more case blocks. This is superficially" " similar to a switch statement in C, Java or JavaScript (and many other " "languages), but it's more similar to pattern matching in languages like Rust" " or Haskell. Only the first pattern that matches gets executed and it can " "also extract components (sequence elements or object attributes) from the " "value into variables." msgstr "" ":keyword:`match` 语句接受一个表达式并把它的值与一个或多个 case 块给出的一系列模式进行比较。这表面上像 C、Java 或 " "JavaScript(以及许多其他程序设计语言)中的 switch 语句,但其实它更像 Rust 或 Haskell " "中的模式匹配。只有第一个匹配的模式会被执行,并且它还可以提取值的组成部分(序列的元素或对象的属性)赋给变量。" #: ../../tutorial/controlflow.rst:294 msgid "" "The simplest form compares a subject value against one or more literals::" msgstr "最简单的形式是将一个主语值与一个或多个字面值进行比较:" #: ../../tutorial/controlflow.rst:296 msgid "" "def http_error(status):\n" " match status:\n" " case 400:\n" " return \"Bad request\"\n" " case 404:\n" " return \"Not found\"\n" " case 418:\n" " return \"I'm a teapot\"\n" " case _:\n" " return \"Something's wrong with the internet\"" msgstr "" "def http_error(status):\n" " match status:\n" " case 400:\n" " return \"Bad request\"\n" " case 404:\n" " return \"Not found\"\n" " case 418:\n" " return \"I'm a teapot\"\n" " case _:\n" " return \"Something's wrong with the internet\"" #: ../../tutorial/controlflow.rst:307 msgid "" "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." msgstr "注意最后一个代码块:“变量名” ``_`` 被作为 *通配符* 并必定会匹配成功。如果没有 case 匹配成功,则不会执行任何分支。" #: ../../tutorial/controlflow.rst:310 msgid "" "You can combine several literals in a single pattern using ``|`` (\"or\")::" msgstr "你可以使用 ``|`` (“ or ”)在一个模式中组合几个字面值::" #: ../../tutorial/controlflow.rst:312 msgid "" "case 401 | 403 | 404:\n" " return \"Not allowed\"" msgstr "" "case 401 | 403 | 404:\n" " return \"Not allowed\"" #: ../../tutorial/controlflow.rst:315 msgid "" "Patterns can look like unpacking assignments, and can be used to bind " "variables::" msgstr "形如解包赋值的模式可被用于绑定变量:" #: ../../tutorial/controlflow.rst:318 msgid "" "# point is an (x, y) tuple\n" "match point:\n" " case (0, 0):\n" " print(\"Origin\")\n" " case (0, y):\n" " print(f\"Y={y}\")\n" " case (x, 0):\n" " print(f\"X={x}\")\n" " case (x, y):\n" " print(f\"X={x}, Y={y}\")\n" " case _:\n" " raise ValueError(\"Not a point\")" msgstr "" "# point 是一个 (x, y) 元组\n" "match point:\n" " case (0, 0):\n" " print(\"Origin\")\n" " case (0, y):\n" " print(f\"Y={y}\")\n" " case (x, 0):\n" " print(f\"X={x}\")\n" " case (x, y):\n" " print(f\"X={x}, Y={y}\")\n" " case _:\n" " raise ValueError(\"Not a point\")" #: ../../tutorial/controlflow.rst:331 msgid "" "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``). The fourth pattern captures two values," " which makes it conceptually similar to the unpacking assignment ``(x, y) = " "point``." msgstr "" "请仔细学习此代码!第一个模式有两个字面值,可视为前述字面值模式的扩展。接下来的两个模式结合了一个字面值和一个变量,变量 *绑定* " "了来自主语(``point``)的一个值。第四个模式捕获了两个值,使其在概念上与解包赋值 ``(x, y) = point`` 类似。" #: ../../tutorial/controlflow.rst:338 msgid "" "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::" msgstr "如果用类组织数据,可以用“类名后接一个参数列表”这种很像构造器的形式,把属性捕获到变量里:" #: ../../tutorial/controlflow.rst:342 msgid "" "class Point:\n" " def __init__(self, x, y):\n" " self.x = x\n" " self.y = y\n" "\n" "def where_is(point):\n" " match point:\n" " case Point(x=0, y=0):\n" " print(\"Origin\")\n" " case Point(x=0, y=y):\n" " print(f\"Y={y}\")\n" " case Point(x=x, y=0):\n" " print(f\"X={x}\")\n" " case Point():\n" " print(\"Somewhere else\")\n" " case _:\n" " print(\"Not a point\")" msgstr "" "class Point:\n" " def __init__(self, x, y):\n" " self.x = x\n" " self.y = y\n" "\n" "def where_is(point):\n" " match point:\n" " case Point(x=0, y=0):\n" " print(\"Origin\")\n" " case Point(x=0, y=y):\n" " print(f\"Y={y}\")\n" " case Point(x=x, y=0):\n" " print(f\"X={x}\")\n" " case Point():\n" " print(\"Somewhere else\")\n" " case _:\n" " print(\"Not a point\")" #: ../../tutorial/controlflow.rst:360 msgid "" "You can use positional parameters with some builtin classes that provide an " "ordering for their attributes (e.g. dataclasses). You can also define a " "specific position for attributes in patterns by setting the " "``__match_args__`` special attribute in your classes. If it's set to (\"x\"," " \"y\"), the following patterns are all equivalent (and all bind the ``y`` " "attribute to the ``var`` variable)::" msgstr "" "你可以在某些为其属性提供了排序的内置类(例如 dataclass)中使用位置参数。 你也可以通过在你的类中设置 ``__match_args__`` " "特殊属性来为模式中的属性定义一个专门的位置。 如果它被设为 (\"x\", \"y\"),则以下模式均为等价的(并且都是将 ``y`` 属性绑定到 " "``var`` 变量)::" #: ../../tutorial/controlflow.rst:366 msgid "" "Point(1, var)\n" "Point(1, y=var)\n" "Point(x=1, y=var)\n" "Point(y=var, x=1)" msgstr "" "Point(1, var)\n" "Point(1, y=var)\n" "Point(x=1, y=var)\n" "Point(y=var, x=1)" #: ../../tutorial/controlflow.rst:371 msgid "" "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. 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." msgstr "" "建议这样来阅读一个模式——通过将其视为赋值语句等号左边的一种扩展形式,来理解各个变量被设为何值。match 语句只会为单一的名称(如上面的 " "``var``)赋值,而不会赋值给带点号的名称(如 ``foo.bar``)、属性名(如上面的 ``x=`` 和 ``y=``)和类名(是通过其后的 " "\"(...)\" 来识别的,如上面的 ``Point``)。" #: ../../tutorial/controlflow.rst:378 msgid "" "Patterns can be arbitrarily nested. For example, if we have a short list of" " Points, with ``__match_args__`` added, we could match it like this::" msgstr "" "模式可以任意嵌套。举例来说,如果我们有一个由 Point 组成的列表,且 Point 添加了 ``__match_args__`` " "时,我们可以这样来匹配它:" #: ../../tutorial/controlflow.rst:381 msgid "" "class Point:\n" " __match_args__ = ('x', 'y')\n" " def __init__(self, x, y):\n" " self.x = x\n" " self.y = y\n" "\n" "match points:\n" " case []:\n" " print(\"No points\")\n" " case [Point(0, 0)]:\n" " print(\"The origin\")\n" " case [Point(x, y)]:\n" " print(f\"Single point {x}, {y}\")\n" " case [Point(0, y1), Point(0, y2)]:\n" " print(f\"Two on the Y axis at {y1}, {y2}\")\n" " case _:\n" " print(\"Something else\")" msgstr "" "class Point:\n" " __match_args__ = ('x', 'y')\n" " def __init__(self, x, y):\n" " self.x = x\n" " self.y = y\n" "\n" "match points:\n" " case []:\n" " print(\"No points\")\n" " case [Point(0, 0)]:\n" " print(\"The origin\")\n" " case [Point(x, y)]:\n" " print(f\"Single point {x}, {y}\")\n" " case [Point(0, y1), Point(0, y2)]:\n" " print(f\"Two on the Y axis at {y1}, {y2}\")\n" " case _:\n" " print(\"Something else\")" #: ../../tutorial/controlflow.rst:399 msgid "" "We can add an ``if`` clause to a pattern, known as a \"guard\". If the " "guard is false, ``match`` goes on to try the next case block. Note that " "value capture happens before the guard is evaluated::" msgstr "" "我们可以向一个模式添加 ``if`` 子句,称为“约束项”。 如果约束项为假值,则 ``match`` 将继续尝试下一个 case 语句块。 " "请注意值的捕获发生在约束项被求值之前。::" #: ../../tutorial/controlflow.rst:403 msgid "" "match point:\n" " case Point(x, y) if x == y:\n" " print(f\"Y=X at {x}\")\n" " case Point(x, y):\n" " print(f\"Not on the diagonal\")" msgstr "" "match point:\n" " case Point(x, y) if x == y:\n" " print(f\"Y=X at {x}\")\n" " case Point(x, y):\n" " print(f\"Not on the diagonal\")" #: ../../tutorial/controlflow.rst:409 msgid "Several other key features of this statement:" msgstr "该语句的一些其它关键特性:" #: ../../tutorial/controlflow.rst:411 msgid "" "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." msgstr "与解包赋值类似,元组和列表模式具有完全相同的含义并且实际上都能匹配任意序列,区别是它们不能匹配迭代器或字符串。" #: ../../tutorial/controlflow.rst:415 msgid "" "Sequence patterns support extended unpacking: ``[x, y, *rest]`` and ``(x, y," " *rest)`` work similar to unpacking assignments. The name after ``*`` may " "also be ``_``, so ``(x, y, *_)`` matches a sequence of at least two items " "without binding the remaining items." msgstr "" "序列模式支持扩展解包:``[x, y, *rest]`` 和 ``(x, y, *rest)`` 和相应的解包赋值做的事是一样的。接在 ``*`` " "后的名称也可以为 ``_``,所以 ``(x, y, *_)`` 匹配含至少两项的序列,而不必绑定剩余的项。" #: ../../tutorial/controlflow.rst:420 msgid "" "Mapping patterns: ``{\"bandwidth\": b, \"latency\": l}`` captures the " "``\"bandwidth\"`` and ``\"latency\"`` values from a dictionary. Unlike " "sequence patterns, extra keys are ignored. An unpacking like ``**rest`` is " "also supported. (But ``**_`` would be redundant, so it is not allowed.)" msgstr "" "映射模式:``{\"bandwidth\": b, \"latency\": l}`` 从字典中捕获 ``\"bandwidth\"`` 和 " "``\"latency\"`` 的值。额外的键会被忽略,这一点与序列模式不同。``**rest`` 这样的解包也支持。(但 ``**_`` " "将会是冗余的,故不允许使用。)" #: ../../tutorial/controlflow.rst:425 msgid "Subpatterns may be captured using the ``as`` keyword::" msgstr "子模式可使用 ``as`` 关键字来捕获::" #: ../../tutorial/controlflow.rst:427 msgid "case (Point(x1, y1), Point(x2, y2) as p2): ..." msgstr "case (Point(x1, y1), Point(x2, y2) as p2): ..." #: ../../tutorial/controlflow.rst:429 msgid "" "will capture the second element of the input as ``p2`` (as long as the input" " is a sequence of two points)" msgstr "将把输入中的第二个元素捕获为 ``p2`` (只要输入是包含两个点的序列)" #: ../../tutorial/controlflow.rst:432 msgid "" "Most literals are compared by equality, however the singletons ``True``, " "``False`` and ``None`` are compared by identity." msgstr "大多数字面值是按相等性比较的,但是单例对象 ``True``、``False`` 和 ``None`` 则是按 id 比较的。" #: ../../tutorial/controlflow.rst:435 msgid "" "Patterns may use named constants. These must be dotted names to prevent " "them from being interpreted as capture variable::" msgstr "模式可以使用具名常量。它们必须作为带点号的名称出现,以防止它们被解释为用于捕获的变量:" #: ../../tutorial/controlflow.rst:438 msgid "" "from enum import Enum\n" "class Color(Enum):\n" " RED = 'red'\n" " GREEN = 'green'\n" " BLUE = 'blue'\n" "\n" "color = Color(input(\"Enter your choice of 'red', 'blue' or 'green': \"))\n" "\n" "match color:\n" " case Color.RED:\n" " print(\"I see red!\")\n" " case Color.GREEN:\n" " print(\"Grass is green\")\n" " case Color.BLUE:\n" " print(\"I'm feeling the blues :(\")" msgstr "" "from enum import Enum\n" "class Color(Enum):\n" " RED = 'red'\n" " GREEN = 'green'\n" " BLUE = 'blue'\n" "\n" "color = Color(input(\"Enter your choice of 'red', 'blue' or 'green': \"))\n" "\n" "match color:\n" " case Color.RED:\n" " print(\"I see red!\")\n" " case Color.GREEN:\n" " print(\"Grass is green\")\n" " case Color.BLUE:\n" " print(\"I'm feeling the blues :(\")" #: ../../tutorial/controlflow.rst:454 msgid "" "For a more detailed explanation and additional examples, you can look into " ":pep:`636` which is written in a tutorial format." msgstr "更详细的说明和更多示例,可参阅以教程格式撰写的 :pep:`636`。" #: ../../tutorial/controlflow.rst:460 msgid "Defining Functions" msgstr "定义函数" #: ../../tutorial/controlflow.rst:462 msgid "" "We can create a function that writes the Fibonacci series to an arbitrary " "boundary::" msgstr "下列代码创建一个可以输出限定数值内的斐波那契数列函数:" #: ../../tutorial/controlflow.rst:465 msgid "" ">>> def fib(n): # write Fibonacci series less than n\n" "... \"\"\"Print a Fibonacci series less than n.\"\"\"\n" "... a, b = 0, 1\n" "... while a < n:\n" "... print(a, end=' ')\n" "... a, b = b, a+b\n" "... print()\n" "...\n" ">>> # Now call the function we just defined:\n" ">>> fib(2000)\n" "0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597" msgstr "" ">>> def fib(n): # 打印小于 n 的斐波那契数列\n" "... \"\"\"Print a Fibonacci series less than n.\"\"\"\n" "... a, b = 0, 1\n" "... while a < n:\n" "... print(a, end=' ')\n" "... a, b = b, a+b\n" "... print()\n" "...\n" ">>> # 现在调用我们刚定义的函数:\n" ">>> fib(2000)\n" "0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597" #: ../../tutorial/controlflow.rst:482 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:487 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:494 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:505 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:512 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:517 msgid "" ">>> fib\n" "\n" ">>> f = fib\n" ">>> f(100)\n" "0 1 1 2 3 5 8 13 21 34 55 89" msgstr "" ">>> fib\n" "\n" ">>> f = fib\n" ">>> f(100)\n" "0 1 1 2 3 5 8 13 21 34 55 89" #: ../../tutorial/controlflow.rst:523 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:530 msgid "" ">>> fib(0)\n" ">>> print(fib(0))\n" "None" msgstr "" ">>> fib(0)\n" ">>> print(fib(0))\n" "None" #: ../../tutorial/controlflow.rst:534 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:537 msgid "" ">>> def fib2(n): # return Fibonacci series up to n\n" "... \"\"\"Return a list containing the Fibonacci series up to n.\"\"\"\n" "... result = []\n" "... a, b = 0, 1\n" "... while a < n:\n" "... result.append(a) # see below\n" "... a, b = b, a+b\n" "... return result\n" "...\n" ">>> f100 = fib2(100) # call it\n" ">>> f100 # write the result\n" "[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]" msgstr "" ">>> def fib2(n): # 返回斐波那契数组直到 n\n" "... \"\"\"Return a list containing the Fibonacci series up to n.\"\"\"\n" "... result = []\n" "... a, b = 0, 1\n" "... while a < n:\n" "... result.append(a) # 见下\n" "... a, b = b, a+b\n" "... return result\n" "...\n" ">>> f100 = fib2(100) # 调用它\n" ">>> f100 # 输出结果\n" "[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]" #: ../../tutorial/controlflow.rst:550 msgid "This example, as usual, demonstrates some new Python features:" msgstr "本例也新引入了一些 Python 功能:" #: ../../tutorial/controlflow.rst:552 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:556 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:571 msgid "More on Defining Functions" msgstr "函数定义详解" #: ../../tutorial/controlflow.rst:573 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:580 msgid "Default Argument Values" msgstr "默认值参数" #: ../../tutorial/controlflow.rst:582 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:586 msgid "" "def ask_ok(prompt, retries=4, reminder='Please try again!'):\n" " while True:\n" " reply = input(prompt)\n" " if reply in {'y', 'ye', 'yes'}:\n" " return True\n" " if reply in {'n', 'no', 'nop', 'nope'}:\n" " return False\n" " retries = retries - 1\n" " if retries < 0:\n" " raise ValueError('invalid user response')\n" " print(reminder)" msgstr "" "def ask_ok(prompt, retries=4, reminder='Please try again!'):\n" " while True:\n" " reply = input(prompt)\n" " if reply in {'y', 'ye', 'yes'}:\n" " return True\n" " if reply in {'n', 'no', 'nop', 'nope'}:\n" " return False\n" " retries = retries - 1\n" " if retries < 0:\n" " raise ValueError('invalid user response')\n" " print(reminder)" #: ../../tutorial/controlflow.rst:598 msgid "This function can be called in several ways:" msgstr "该函数可以用以下方式调用:" #: ../../tutorial/controlflow.rst:600 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:602 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:604 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:607 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:610 msgid "" "The default values are evaluated at the point of function definition in the " "*defining* scope, so that ::" msgstr "默认值在 *定义* 作用域里的函数定义中求值,所以:" #: ../../tutorial/controlflow.rst:613 msgid "" "i = 5\n" "\n" "def f(arg=i):\n" " print(arg)\n" "\n" "i = 6\n" "f()" msgstr "" "i = 5\n" "\n" "def f(arg=i):\n" " print(arg)\n" "\n" "i = 6\n" "f()" #: ../../tutorial/controlflow.rst:621 msgid "will print ``5``." msgstr "上例输出的是 ``5``。" #: ../../tutorial/controlflow.rst:623 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:628 msgid "" "def f(a, L=[]):\n" " L.append(a)\n" " return L\n" "\n" "print(f(1))\n" "print(f(2))\n" "print(f(3))" msgstr "" "def f(a, L=[]):\n" " L.append(a)\n" " return L\n" "\n" "print(f(1))\n" "print(f(2))\n" "print(f(3))" #: ../../tutorial/controlflow.rst:636 msgid "This will print ::" msgstr "输出结果如下:" #: ../../tutorial/controlflow.rst:638 msgid "" "[1]\n" "[1, 2]\n" "[1, 2, 3]" msgstr "" "[1]\n" "[1, 2]\n" "[1, 2, 3]" #: ../../tutorial/controlflow.rst:642 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:645 msgid "" "def f(a, L=None):\n" " if L is None:\n" " L = []\n" " L.append(a)\n" " return L" msgstr "" "def f(a, L=None):\n" " if L is None:\n" " L = []\n" " L.append(a)\n" " return L" #: ../../tutorial/controlflow.rst:655 msgid "Keyword Arguments" msgstr "关键字参数" #: ../../tutorial/controlflow.rst:657 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:660 msgid "" "def parrot(voltage, state='a stiff', action='voom', type='Norwegian Blue'):\n" " print(\"-- This parrot wouldn't\", action, end=' ')\n" " print(\"if you put\", voltage, \"volts through it.\")\n" " print(\"-- Lovely plumage, the\", type)\n" " print(\"-- It's\", state, \"!\")" msgstr "" "def parrot(voltage, state='a stiff', action='voom', type='Norwegian Blue'):\n" " print(\"-- This parrot wouldn't\", action, end=' ')\n" " print(\"if you put\", voltage, \"volts through it.\")\n" " print(\"-- Lovely plumage, the\", type)\n" " print(\"-- It's\", state, \"!\")" #: ../../tutorial/controlflow.rst:666 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:670 msgid "" "parrot(1000) # 1 positional argument\n" "parrot(voltage=1000) # 1 keyword argument\n" "parrot(voltage=1000000, action='VOOOOOM') # 2 keyword arguments\n" "parrot(action='VOOOOOM', voltage=1000000) # 2 keyword arguments\n" "parrot('a million', 'bereft of life', 'jump') # 3 positional arguments\n" "parrot('a thousand', state='pushing up the daisies') # 1 positional, 1 keyword" msgstr "" "parrot(1000) # 1 个位置参数\n" "parrot(voltage=1000) # 1 个关键字参数\n" "parrot(voltage=1000000, action='VOOOOOM') # 2 个关键字参数\n" "parrot(action='VOOOOOM', voltage=1000000) # 2 个关键字参数\n" "parrot('a million', 'bereft of life', 'jump') # 3 个位置参数\n" "parrot('a thousand', state='pushing up the daisies') # 1 个位置参数,1 个关键字参数" #: ../../tutorial/controlflow.rst:677 msgid "but all the following calls would be invalid::" msgstr "以下调用函数的方式都无效:" #: ../../tutorial/controlflow.rst:679 msgid "" "parrot() # required argument missing\n" "parrot(voltage=5.0, 'dead') # non-keyword argument after a keyword argument\n" "parrot(110, voltage=220) # duplicate value for the same argument\n" "parrot(actor='John Cleese') # unknown keyword argument" msgstr "" "parrot() # 缺失必需的参数\n" "parrot(voltage=5.0, 'dead') # 关键字参数后存在非关键字参数\n" "parrot(110, voltage=220) # 同一个参数重复的值\n" "parrot(actor='John Cleese') # 未知的关键字参数" #: ../../tutorial/controlflow.rst:684 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:692 msgid "" ">>> def function(a):\n" "... pass\n" "...\n" ">>> function(0, a=0)\n" "Traceback (most recent call last):\n" " File \"\", line 1, in \n" "TypeError: function() got multiple values for argument 'a'" msgstr "" ">>> def function(a):\n" "... pass\n" "...\n" ">>> function(0, a=0)\n" "Traceback (most recent call last):\n" " File \"\", line 1, in \n" "TypeError: function() got multiple values for argument 'a'" #: ../../tutorial/controlflow.rst:700 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:708 msgid "" "def cheeseshop(kind, *arguments, **keywords):\n" " print(\"-- Do you have any\", kind, \"?\")\n" " print(\"-- I'm sorry, we're all out of\", kind)\n" " for arg in arguments:\n" " print(arg)\n" " print(\"-\" * 40)\n" " for kw in keywords:\n" " print(kw, \":\", keywords[kw])" msgstr "" "def cheeseshop(kind, *arguments, **keywords):\n" " print(\"-- Do you have any\", kind, \"?\")\n" " print(\"-- I'm sorry, we're all out of\", kind)\n" " for arg in arguments:\n" " print(arg)\n" " print(\"-\" * 40)\n" " for kw in keywords:\n" " print(kw, \":\", keywords[kw])" #: ../../tutorial/controlflow.rst:717 msgid "It could be called like this::" msgstr "该函数可以用如下方式调用:" #: ../../tutorial/controlflow.rst:719 msgid "" "cheeseshop(\"Limburger\", \"It's very runny, sir.\",\n" " \"It's really very, VERY runny, sir.\",\n" " shopkeeper=\"Michael Palin\",\n" " client=\"John Cleese\",\n" " sketch=\"Cheese Shop Sketch\")" msgstr "" "cheeseshop(\"Limburger\", \"It's very runny, sir.\",\n" " \"It's really very, VERY runny, sir.\",\n" " shopkeeper=\"Michael Palin\",\n" " client=\"John Cleese\",\n" " sketch=\"Cheese Shop Sketch\")" #: ../../tutorial/controlflow.rst:725 msgid "and of course it would print:" msgstr "输出结果如下:" #: ../../tutorial/controlflow.rst:727 msgid "" "-- Do you have any Limburger ?\n" "-- I'm sorry, we're all out of Limburger\n" "It's very runny, sir.\n" "It's really very, VERY runny, sir.\n" "----------------------------------------\n" "shopkeeper : Michael Palin\n" "client : John Cleese\n" "sketch : Cheese Shop Sketch" msgstr "" "-- Do you have any Limburger ?\n" "-- I'm sorry, we're all out of Limburger\n" "It's very runny, sir.\n" "It's really very, VERY runny, sir.\n" "----------------------------------------\n" "shopkeeper : Michael Palin\n" "client : John Cleese\n" "sketch : Cheese Shop Sketch" #: ../../tutorial/controlflow.rst:738 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:742 msgid "Special parameters" msgstr "特殊参数" #: ../../tutorial/controlflow.rst:744 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:750 msgid "A function definition may look like:" msgstr "函数定义如下:" #: ../../tutorial/controlflow.rst:752 msgid "" "def f(pos1, pos2, /, pos_or_kwd, *, kwd1, kwd2):\n" " ----------- ---------- ----------\n" " | | |\n" " | Positional or keyword |\n" " | - Keyword only\n" " -- Positional only" msgstr "" "def f(pos1, pos2, /, pos_or_kwd, *, kwd1, kwd2):\n" " ----------- ---------- ----------\n" " | | |\n" " | 位置或关键字 |\n" " | - 仅限关键字\n" " -- 仅限位置" #: ../../tutorial/controlflow.rst:761 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:768 msgid "Positional-or-Keyword Arguments" msgstr "位置或关键字参数" #: ../../tutorial/controlflow.rst:770 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:775 msgid "Positional-Only Parameters" msgstr "仅位置参数" #: ../../tutorial/controlflow.rst:777 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:785 msgid "" "Parameters following the ``/`` may be *positional-or-keyword* or *keyword-" "only*." msgstr "``/`` 后可以是 *位置或关键字* 或 *仅限关键字* 形参。" #: ../../tutorial/controlflow.rst:789 msgid "Keyword-Only Arguments" msgstr "仅限关键字参数" #: ../../tutorial/controlflow.rst:791 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:797 msgid "Function Examples" msgstr "函数示例" #: ../../tutorial/controlflow.rst:799 msgid "" "Consider the following example function definitions paying close attention " "to the markers ``/`` and ``*``::" msgstr "请看下面的函数定义示例,注意 ``/`` 和 ``*`` 标记:" #: ../../tutorial/controlflow.rst:802 msgid "" ">>> def standard_arg(arg):\n" "... print(arg)\n" "...\n" ">>> def pos_only_arg(arg, /):\n" "... print(arg)\n" "...\n" ">>> def kwd_only_arg(*, arg):\n" "... print(arg)\n" "...\n" ">>> def combined_example(pos_only, /, standard, *, kwd_only):\n" "... print(pos_only, standard, kwd_only)" msgstr "" ">>> def standard_arg(arg):\n" "... print(arg)\n" "...\n" ">>> def pos_only_arg(arg, /):\n" "... print(arg)\n" "...\n" ">>> def kwd_only_arg(*, arg):\n" "... print(arg)\n" "...\n" ">>> def combined_example(pos_only, /, standard, *, kwd_only):\n" "... print(pos_only, standard, kwd_only)" #: ../../tutorial/controlflow.rst:815 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:819 msgid "" ">>> standard_arg(2)\n" "2\n" "\n" ">>> standard_arg(arg=2)\n" "2" msgstr "" ">>> standard_arg(2)\n" "2\n" "\n" ">>> standard_arg(arg=2)\n" "2" #: ../../tutorial/controlflow.rst:825 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:828 msgid "" ">>> pos_only_arg(1)\n" "1\n" "\n" ">>> pos_only_arg(arg=1)\n" "Traceback (most recent call last):\n" " File \"\", line 1, in \n" "TypeError: pos_only_arg() got some positional-only arguments passed as keyword arguments: 'arg'" msgstr "" ">>> pos_only_arg(1)\n" "1\n" "\n" ">>> pos_only_arg(arg=1)\n" "Traceback (most recent call last):\n" " File \"\", line 1, in \n" "TypeError: pos_only_arg() got some positional-only arguments passed as keyword arguments: 'arg'" #: ../../tutorial/controlflow.rst:836 msgid "" "The third function ``kwd_only_arg`` only allows keyword arguments as " "indicated by a ``*`` in the function definition::" msgstr "第三个函数 ``kwd_only_arg`` 如在函数定义中通过 ``*`` 所指明的那样只允许关键字参数。" #: ../../tutorial/controlflow.rst:839 msgid "" ">>> kwd_only_arg(3)\n" "Traceback (most recent call last):\n" " File \"\", line 1, in \n" "TypeError: kwd_only_arg() takes 0 positional arguments but 1 was given\n" "\n" ">>> kwd_only_arg(arg=3)\n" "3" msgstr "" ">>> kwd_only_arg(3)\n" "Traceback (most recent call last):\n" " File \"\", line 1, in \n" "TypeError: kwd_only_arg() takes 0 positional arguments but 1 was given\n" "\n" ">>> kwd_only_arg(arg=3)\n" "3" #: ../../tutorial/controlflow.rst:847 msgid "" "And the last uses all three calling conventions in the same function " "definition::" msgstr "最后一个函数在同一个函数定义中,使用了全部三种调用惯例:" #: ../../tutorial/controlflow.rst:850 msgid "" ">>> combined_example(1, 2, 3)\n" "Traceback (most recent call last):\n" " File \"\", line 1, in \n" "TypeError: combined_example() takes 2 positional arguments but 3 were given\n" "\n" ">>> combined_example(1, 2, kwd_only=3)\n" "1 2 3\n" "\n" ">>> combined_example(1, standard=2, kwd_only=3)\n" "1 2 3\n" "\n" ">>> combined_example(pos_only=1, standard=2, kwd_only=3)\n" "Traceback (most recent call last):\n" " File \"\", line 1, in \n" "TypeError: combined_example() got some positional-only arguments passed as keyword arguments: 'pos_only'" msgstr "" ">>> combined_example(1, 2, 3)\n" "Traceback (most recent call last):\n" " File \"\", line 1, in \n" "TypeError: combined_example() takes 2 positional arguments but 3 were given\n" "\n" ">>> combined_example(1, 2, kwd_only=3)\n" "1 2 3\n" "\n" ">>> combined_example(1, standard=2, kwd_only=3)\n" "1 2 3\n" "\n" ">>> combined_example(pos_only=1, standard=2, kwd_only=3)\n" "Traceback (most recent call last):\n" " File \"\", line 1, in \n" "TypeError: combined_example() got some positional-only arguments passed as keyword arguments: 'pos_only'" #: ../../tutorial/controlflow.rst:867 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:869 msgid "" "def foo(name, **kwds):\n" " return 'name' in kwds" msgstr "" "def foo(name, **kwds):\n" " return 'name' in kwds" #: ../../tutorial/controlflow.rst:872 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:875 msgid "" ">>> foo(1, **{'name': 2})\n" "Traceback (most recent call last):\n" " File \"\", line 1, in \n" "TypeError: foo() got multiple values for argument 'name'\n" ">>>" msgstr "" ">>> foo(1, **{'name': 2})\n" "Traceback (most recent call last):\n" " File \"\", line 1, in \n" "TypeError: foo() got multiple values for argument 'name'\n" ">>>" #: ../../tutorial/controlflow.rst:881 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:883 msgid "" ">>> def foo(name, /, **kwds):\n" "... return 'name' in kwds\n" "...\n" ">>> foo(1, **{'name': 2})\n" "True" msgstr "" ">>> def foo(name, /, **kwds):\n" "... return 'name' in kwds\n" "...\n" ">>> foo(1, **{'name': 2})\n" "True" #: ../../tutorial/controlflow.rst:889 msgid "" "In other words, the names of positional-only parameters can be used in " "``**kwds`` without ambiguity." msgstr "换句话说,仅限位置形参的名称可以在 ``**kwds`` 中使用,而不产生歧义。" #: ../../tutorial/controlflow.rst:894 msgid "Recap" msgstr "小结" #: ../../tutorial/controlflow.rst:896 msgid "" "The use case will determine which parameters to use in the function " "definition::" msgstr "以下用例决定哪些形参可以用于函数定义:" #: ../../tutorial/controlflow.rst:898 msgid "def f(pos1, pos2, /, pos_or_kwd, *, kwd1, kwd2):" msgstr "def f(pos1, pos2, /, pos_or_kwd, *, kwd1, kwd2):" #: ../../tutorial/controlflow.rst:900 msgid "As guidance:" msgstr "说明:" #: ../../tutorial/controlflow.rst:902 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:907 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:910 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:916 msgid "Arbitrary Argument Lists" msgstr "任意实参列表" #: ../../tutorial/controlflow.rst:921 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:926 msgid "" "def write_multiple_items(file, separator, *args):\n" " file.write(separator.join(args))" msgstr "" "def write_multiple_items(file, separator, *args):\n" " file.write(separator.join(args))" #: ../../tutorial/controlflow.rst:930 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 "" "*variadic* 参数用于采集传递给函数的所有剩余参数,因此,它们通常在形参列表的末尾。``*args`` " "形参后的任何形式参数只能是仅限关键字参数,即只能用作关键字参数,不能用作位置参数:" #: ../../tutorial/controlflow.rst:936 msgid "" ">>> def concat(*args, sep=\"/\"):\n" "... return sep.join(args)\n" "...\n" ">>> concat(\"earth\", \"mars\", \"venus\")\n" "'earth/mars/venus'\n" ">>> concat(\"earth\", \"mars\", \"venus\", sep=\".\")\n" "'earth.mars.venus'" msgstr "" ">>> def concat(*args, sep=\"/\"):\n" "... return sep.join(args)\n" "...\n" ">>> concat(\"earth\", \"mars\", \"venus\")\n" "'earth/mars/venus'\n" ">>> concat(\"earth\", \"mars\", \"venus\", sep=\".\")\n" "'earth.mars.venus'" #: ../../tutorial/controlflow.rst:947 msgid "Unpacking Argument Lists" msgstr "解包实参列表" #: ../../tutorial/controlflow.rst:949 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:956 msgid "" ">>> list(range(3, 6)) # normal call with separate arguments\n" "[3, 4, 5]\n" ">>> args = [3, 6]\n" ">>> list(range(*args)) # call with arguments unpacked from a list\n" "[3, 4, 5]" msgstr "" ">>> list(range(3, 6)) # 附带两个参数的正常调用\n" "[3, 4, 5]\n" ">>> args = [3, 6]\n" ">>> list(range(*args)) # 附带从一个列表解包的参数的调用\n" "[3, 4, 5]" #: ../../tutorial/controlflow.rst:965 msgid "" "In the same fashion, dictionaries can deliver keyword arguments with the " "``**``\\ -operator::" msgstr "同样,字典可以用 ``**`` 操作符传递关键字参数:" #: ../../tutorial/controlflow.rst:968 msgid "" ">>> def parrot(voltage, state='a stiff', action='voom'):\n" "... print(\"-- This parrot wouldn't\", action, end=' ')\n" "... print(\"if you put\", voltage, \"volts through it.\", end=' ')\n" "... print(\"E's\", state, \"!\")\n" "...\n" ">>> d = {\"voltage\": \"four million\", \"state\": \"bleedin' demised\", \"action\": \"VOOM\"}\n" ">>> parrot(**d)\n" "-- This parrot wouldn't VOOM if you put four million volts through it. E's bleedin' demised !" msgstr "" ">>> def parrot(voltage, state='a stiff', action='voom'):\n" "... print(\"-- This parrot wouldn't\", action, end=' ')\n" "... print(\"if you put\", voltage, \"volts through it.\", end=' ')\n" "... print(\"E's\", state, \"!\")\n" "...\n" ">>> d = {\"voltage\": \"four million\", \"state\": \"bleedin' demised\", \"action\": \"VOOM\"}\n" ">>> parrot(**d)\n" "-- This parrot wouldn't VOOM if you put four million volts through it. E's bleedin' demised !" #: ../../tutorial/controlflow.rst:981 msgid "Lambda Expressions" msgstr "Lambda 表达式" #: ../../tutorial/controlflow.rst:983 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:991 msgid "" ">>> def make_incrementor(n):\n" "... return lambda x: x + n\n" "...\n" ">>> f = make_incrementor(42)\n" ">>> f(0)\n" "42\n" ">>> f(1)\n" "43" msgstr "" ">>> def make_incrementor(n):\n" "... return lambda x: x + n\n" "...\n" ">>> f = make_incrementor(42)\n" ">>> f(0)\n" "42\n" ">>> f(1)\n" "43" #: ../../tutorial/controlflow.rst:1000 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:1003 msgid "" ">>> pairs = [(1, 'one'), (2, 'two'), (3, 'three'), (4, 'four')]\n" ">>> pairs.sort(key=lambda pair: pair[1])\n" ">>> pairs\n" "[(4, 'four'), (1, 'one'), (3, 'three'), (2, 'two')]" msgstr "" ">>> pairs = [(1, 'one'), (2, 'two'), (3, 'three'), (4, 'four')]\n" ">>> pairs.sort(key=lambda pair: pair[1])\n" ">>> pairs\n" "[(4, 'four'), (1, 'one'), (3, 'three'), (2, 'two')]" #: ../../tutorial/controlflow.rst:1012 msgid "Documentation Strings" msgstr "文档字符串" #: ../../tutorial/controlflow.rst:1019 msgid "" "Here are some conventions about the content and formatting of documentation " "strings." msgstr "以下是文档字符串内容和格式的约定。" #: ../../tutorial/controlflow.rst:1022 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:1028 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:1033 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:1045 msgid "Here is an example of a multi-line docstring::" msgstr "下面是多行文档字符串的一个例子:" #: ../../tutorial/controlflow.rst:1047 msgid "" ">>> def my_function():\n" "... \"\"\"Do nothing, but document it.\n" "...\n" "... No, really, it doesn't do anything.\n" "... \"\"\"\n" "... pass\n" "...\n" ">>> print(my_function.__doc__)\n" "Do nothing, but document it.\n" "\n" " No, really, it doesn't do anything." msgstr "" ">>> def my_function():\n" "... \"\"\"Do nothing, but document it.\n" "...\n" "... No, really, it doesn't do anything.\n" "... \"\"\"\n" "... pass\n" "...\n" ">>> print(my_function.__doc__)\n" "Do nothing, but document it.\n" "\n" " No, really, it doesn't do anything." #: ../../tutorial/controlflow.rst:1063 msgid "Function Annotations" msgstr "函数注解" #: ../../tutorial/controlflow.rst:1071 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:1075 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:1084 msgid "" ">>> def f(ham: str, eggs: str = 'eggs') -> str:\n" "... print(\"Annotations:\", f.__annotations__)\n" "... print(\"Arguments:\", ham, eggs)\n" "... return ham + ' and ' + eggs\n" "...\n" ">>> f('spam')\n" "Annotations: {'ham': , 'return': , 'eggs': }\n" "Arguments: spam eggs\n" "'spam and eggs'" msgstr "" ">>> def f(ham: str, eggs: str = 'eggs') -> str:\n" "... print(\"Annotations:\", f.__annotations__)\n" "... print(\"Arguments:\", ham, eggs)\n" "... return ham + ' and ' + eggs\n" "...\n" ">>> f('spam')\n" "Annotations: {'ham': , 'return': , 'eggs': }\n" "Arguments: spam eggs\n" "'spam and eggs'" #: ../../tutorial/controlflow.rst:1097 msgid "Intermezzo: Coding Style" msgstr "小插曲:编码风格" #: ../../tutorial/controlflow.rst:1102 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:1108 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:1113 msgid "Use 4-space indentation, and no tabs." msgstr "缩进,用 4 个空格,不要用制表符。" #: ../../tutorial/controlflow.rst:1115 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:1119 msgid "Wrap lines so that they don't exceed 79 characters." msgstr "换行,一行不超过 79 个字符。" #: ../../tutorial/controlflow.rst:1121 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:1124 msgid "" "Use blank lines to separate functions and classes, and larger blocks of code" " inside functions." msgstr "用空行分隔函数和类,及函数内较大的代码块。" #: ../../tutorial/controlflow.rst:1127 msgid "When possible, put comments on a line of their own." msgstr "最好把注释放到单独一行。" #: ../../tutorial/controlflow.rst:1129 msgid "Use docstrings." msgstr "使用文档字符串。" #: ../../tutorial/controlflow.rst:1131 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:1134 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:1139 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:1143 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:1149 msgid "Footnotes" msgstr "备注" #: ../../tutorial/controlflow.rst:1150 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 "实际上,*对象引用调用* 这种说法更好,因为,传递的是可变对象时,调用者能发现被调者做出的任何更改(插入列表的元素)。" #: ../../tutorial/controlflow.rst:48 msgid "statement" msgstr "statement -- 语句" #: ../../tutorial/controlflow.rst:48 msgid "for" msgstr "for" #: ../../tutorial/controlflow.rst:477 ../../tutorial/controlflow.rst:1014 msgid "documentation strings" msgstr "文档字符串" #: ../../tutorial/controlflow.rst:477 ../../tutorial/controlflow.rst:1014 msgid "docstrings" msgstr "文档字符串" #: ../../tutorial/controlflow.rst:477 ../../tutorial/controlflow.rst:1014 msgid "strings, documentation" msgstr "字符串,文档" #: ../../tutorial/controlflow.rst:918 msgid "* (asterisk)" msgstr "* (星号)" #: ../../tutorial/controlflow.rst:918 ../../tutorial/controlflow.rst:962 msgid "in function calls" msgstr "在函数调用中" #: ../../tutorial/controlflow.rst:962 msgid "**" msgstr "**" #: ../../tutorial/controlflow.rst:1066 msgid "function" msgstr "function -- 函数" #: ../../tutorial/controlflow.rst:1066 msgid "annotations" msgstr "annotations" #: ../../tutorial/controlflow.rst:1066 msgid "->" msgstr "->" #: ../../tutorial/controlflow.rst:1066 msgid "function annotations" msgstr "函数标注" #: ../../tutorial/controlflow.rst:1066 msgid ": (colon)" msgstr ": (冒号)" #: ../../tutorial/controlflow.rst:1100 msgid "coding" msgstr "编码" #: ../../tutorial/controlflow.rst:1100 msgid "style" msgstr "style"