# Copyright (C) 2001-2024, Python Software Foundation # This file is distributed under the same license as the Python package. # # Translators: # jerrychen , 2016 # Ching-Lung Chuang, 2015 # hsiao yi , 2016 msgid "" msgstr "" "Project-Id-Version: Python 3.12\n" "Report-Msgid-Bugs-To: \n" "POT-Creation-Date: 2024-09-03 11:11+0800\n" "PO-Revision-Date: 2024-04-25 14:17+0800\n" "Last-Translator: KNChiu \n" "Language-Team: Chinese - TAIWAN (https://github.com/python/python-docs-zh-" "tw)\n" "Language: zh_TW\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" "Plural-Forms: nplurals=1; plural=0;\n" "X-Generator: Poedit 3.4.2\n" #: ../../faq/programming.rst:5 msgid "Programming FAQ" msgstr "程式開發常見問答集" #: ../../faq/programming.rst:8 msgid "Contents" msgstr "目錄" #: ../../faq/programming.rst:12 msgid "General Questions" msgstr "常見問題" #: ../../faq/programming.rst:15 msgid "" "Is there a source code level debugger with breakpoints, single-stepping, " "etc.?" msgstr "是否有可以使用在程式碼階段,具有中斷點,步驟執行等功能的除錯器?" #: ../../faq/programming.rst:17 ../../faq/programming.rst:58 msgid "Yes." msgstr "有的。" #: ../../faq/programming.rst:19 msgid "" "Several debuggers for Python are described below, and the built-in function :" "func:`breakpoint` allows you to drop into any of them." msgstr "" "下面描述了幾個 Python 除錯器,內建函式 :func:`breakpoint` 允許你進入其中任何" "一個。" #: ../../faq/programming.rst:22 msgid "" "The pdb module is a simple but adequate console-mode debugger for Python. It " "is part of the standard Python library, and is :mod:`documented in the " "Library Reference Manual `. You can also write your own debugger by " "using the code for pdb as an example." msgstr "" "pdb 模組是一個簡單但足夠的 Python 控制台模式除錯器。它是標準 Python 函式庫的" "一部分,並\\ :mod:`記錄在函式庫參考手冊 `\\ 中。你也可以參考 pdb 的程式" "碼作為範例來編寫自己的除錯器。" #: ../../faq/programming.rst:27 msgid "" "The IDLE interactive development environment, which is part of the standard " "Python distribution (normally available as `Tools/scripts/idle3 `_), includes a " "graphical debugger." msgstr "" "IDLE 交互式開發環境,它是標準 Python 發行版的一部分(通常作為 `Tools/scripts/" "idle3 `_ 提" "供),包括一個圖形除錯器。" #: ../../faq/programming.rst:32 msgid "" "PythonWin is a Python IDE that includes a GUI debugger based on pdb. The " "PythonWin debugger colors breakpoints and has quite a few cool features such " "as debugging non-PythonWin programs. PythonWin is available as part of " "`pywin32 `_ project and as a part of " "the `ActivePython `_ " "distribution." msgstr "" "PythonWin 是一個 Python IDE,它包含一個基於 pdb 的 GUI 除錯器。 PythonWin 除" "錯器為斷點著色並具有許多很酷的功能,例如除錯非 PythonWin 程式。 PythonWin 作" "為 `pywin32 `_ 專案的一部分和作為 " "`ActivePython `_ 的一部分發佈。" #: ../../faq/programming.rst:39 msgid "" "`Eric `_ is an IDE built on PyQt and " "the Scintilla editing component." msgstr "" "`Eric `_ 是一個基於 PyQt 和 Scintilla " "編輯元件所建構的 IDE。" #: ../../faq/programming.rst:42 msgid "" "`trepan3k `_ is a gdb-like " "debugger." msgstr "" "`trepan3k `_ 是一個類似 gdb 的除錯" "器。" #: ../../faq/programming.rst:44 msgid "" "`Visual Studio Code `_ is an IDE with " "debugging tools that integrates with version-control software." msgstr "" "`Visual Studio Code `_ 是一個整合了版本控制軟" "體與除錯工具的 IDE。" #: ../../faq/programming.rst:47 msgid "" "There are a number of commercial Python IDEs that include graphical " "debuggers. They include:" msgstr "有數個商業化Python整合化開發工具包含圖形除錯功能。這些包含:" #: ../../faq/programming.rst:50 msgid "`Wing IDE `_" msgstr "`Wing IDE `_" #: ../../faq/programming.rst:51 msgid "`Komodo IDE `_" msgstr "`Komodo IDE `_" #: ../../faq/programming.rst:52 msgid "`PyCharm `_" msgstr "`PyCharm `_" #: ../../faq/programming.rst:56 msgid "Are there tools to help find bugs or perform static analysis?" msgstr "有沒有工具能夠幫忙找 bug 或執行靜態分析?" #: ../../faq/programming.rst:60 msgid "" "`Pylint `_ and `Pyflakes " "`_ do basic checking that will help you " "catch bugs sooner." msgstr "" "`Pylint `_ 和 `Pyflakes " "`_ 進行基本檢查以幫助你儘早抓出錯誤。" #: ../../faq/programming.rst:64 msgid "" "Static type checkers such as `Mypy `_, `Pyre " "`_, and `Pytype `_ can check type hints in Python source code." msgstr "" "靜態型別檢查器,例如 `Mypy `_、`Pyre `_ 和 `Pytype `_ 可以檢查 " "Python 原始碼中的型別提示。" #: ../../faq/programming.rst:73 msgid "How can I create a stand-alone binary from a Python script?" msgstr "如何從 Python 腳本建立獨立的二進位檔案?" #: ../../faq/programming.rst:75 #, fuzzy msgid "" "You don't need the ability to compile Python to C code if all you want is a " "stand-alone program that users can download and run without having to " "install the Python distribution first. There are a number of tools that " "determine the set of modules required by a program and bind these modules " "together with a Python binary to produce a single executable." msgstr "" "如果你想要的只是一個使用者可以下載並運行而無需先安裝 Python 發行版的獨立程" "式,則不需要將 Python 編譯為 C 程式碼的能力。有許多工具可以確定程式所需的模組" "集,並將這些模組與 Python 二進製檔案綁定在一起以生成單個可執行檔案。" #: ../../faq/programming.rst:81 #, fuzzy msgid "" "One is to use the freeze tool, which is included in the Python source tree " "as `Tools/freeze `_. It converts Python byte code to C arrays; with a C compiler you " "can embed all your modules into a new program, which is then linked with the " "standard Python modules." msgstr "" "一種是使用凍結工具,它作為 `Tools/freeze `_ 包含在 Python 源程式碼樹中。它將 Python 位元組碼轉" "換為 C 數組;使用 C 編譯器,你可以將所有模組嵌入到一個新程式中,然後將其與標" "準 Python 模組鏈接。" #: ../../faq/programming.rst:87 #, fuzzy msgid "" "It works by scanning your source recursively for import statements (in both " "forms) and looking for the modules in the standard Python path as well as in " "the source directory (for built-in modules). It then turns the bytecode for " "modules written in Python into C code (array initializers that can be turned " "into code objects using the marshal module) and creates a custom-made config " "file that only contains those built-in modules which are actually used in " "the program. It then compiles the generated C code and links it with the " "rest of the Python interpreter to form a self-contained binary which acts " "exactly like your script." msgstr "" "它的工作原理是遞迴地掃描你的源程式碼以查詢引入陳述式(兩種形式)並在標準 " "Python 路徑和源目錄(對於內建模組)中查詢模組。然後它將用 Python 編寫的模組的" "位元組碼轉換為 C 程式碼(數組初始化器可以使用 marshal 模組轉換為程式碼物件)" "並建立一個定制的配置檔案,該檔案僅包含那些實際使用的內建模組程式。然後它編譯" "生成的 C 程式碼並將其與 Python 直譯器的其餘部分鏈接以形成一個獨立的二進製檔" "案,其行為與你的腳本完全一樣。" #: ../../faq/programming.rst:96 msgid "" "The following packages can help with the creation of console and GUI " "executables:" msgstr "以下套件可以幫助建立 console 和 GUI 可執行檔案:" #: ../../faq/programming.rst:99 msgid "`Nuitka `_ (Cross-platform)" msgstr "`Nuitka `_\\ (跨平台)" #: ../../faq/programming.rst:100 msgid "`PyInstaller `_ (Cross-platform)" msgstr "`PyInstaller `_\\ (跨平台)" #: ../../faq/programming.rst:101 msgid "" "`PyOxidizer `_ (Cross-platform)" msgstr "" "`PyOxidizer `_\\ (跨平台)" #: ../../faq/programming.rst:102 msgid "" "`cx_Freeze `_ (Cross-platform)" msgstr "" "`cx_Freeze `_\\ (跨平台)" #: ../../faq/programming.rst:103 msgid "`py2app `_ (macOS only)" msgstr "`py2app `_\\ (僅限 macOS)" #: ../../faq/programming.rst:104 msgid "`py2exe `_ (Windows only)" msgstr "`py2exe `_\\ (僅限 Windows)" #: ../../faq/programming.rst:107 msgid "Are there coding standards or a style guide for Python programs?" msgstr "Python 程式碼是否有編碼標準或風格指南?" #: ../../faq/programming.rst:109 msgid "" "Yes. The coding style required for standard library modules is documented " "as :pep:`8`." msgstr "是的。標準函式庫模組所需的編碼風格稱為 :pep:`8`。" #: ../../faq/programming.rst:114 msgid "Core Language" msgstr "核心語言" #: ../../faq/programming.rst:119 msgid "Why am I getting an UnboundLocalError when the variable has a value?" msgstr "為什麼當變數有值時,我仍得到錯誤訊息 UnboundLocalError?" #: ../../faq/programming.rst:121 #, fuzzy msgid "" "It can be a surprise to get the :exc:`UnboundLocalError` in previously " "working code when it is modified by adding an assignment statement somewhere " "in the body of a function." msgstr "" "當透過在函式主體的某處新增賦值陳述式修改以前的工作程式碼時,在以前的工作程式" "碼中得到 :exc:`UnboundLocalError` 可能會令人驚訝。" #: ../../faq/programming.rst:125 msgid "This code:" msgstr "這段程式碼:" #: ../../faq/programming.rst:134 msgid "works, but this code:" msgstr "可以執行,但是這段程式:" #: ../../faq/programming.rst:141 msgid "results in an :exc:`!UnboundLocalError`:" msgstr "導致 :exc:`!UnboundLocalError`:" #: ../../faq/programming.rst:148 #, fuzzy msgid "" "This is because when you make an assignment to a variable in a scope, that " "variable becomes local to that scope and shadows any similarly named " "variable in the outer scope. Since the last statement in foo assigns a new " "value to ``x``, the compiler recognizes it as a local variable. " "Consequently when the earlier ``print(x)`` attempts to print the " "uninitialized local variable and an error results." msgstr "" "這是因為當你對作用域中的變數進行賦值時,該變數將成為該作用域的局部變數,並隱" "藏外部作用域中任何類似命名的變數。由於 foo 中的最後一條陳述式為 ``x`` 分配了" "一個新值,因此編譯器將其識別為局部變數。因此,當較早的 ``print(x)`` 嘗試印出" "未初始化的局部變數並產生錯誤時。" #: ../../faq/programming.rst:155 msgid "" "In the example above you can access the outer scope variable by declaring it " "global:" msgstr "在上面的示例中,你可以透過將其聲明為全域變數來存取外部範圍變數:" #: ../../faq/programming.rst:167 #, fuzzy msgid "" "This explicit declaration is required in order to remind you that (unlike " "the superficially analogous situation with class and instance variables) you " "are actually modifying the value of the variable in the outer scope:" msgstr "" "需要此顯式聲明是為了提醒你(與類別和實例變數表面上類似的情況不同)你實際上是" "在外部範圍內修改變數的值:" #: ../../faq/programming.rst:174 #, fuzzy msgid "" "You can do a similar thing in a nested scope using the :keyword:`nonlocal` " "keyword:" msgstr "你可以使用 :keyword:`nonlocal` 關鍵字在嵌套範圍內做類似的事情:" #: ../../faq/programming.rst:192 msgid "What are the rules for local and global variables in Python?" msgstr "Python 的區域變數和全域變數有什麼規則?" #: ../../faq/programming.rst:194 #, fuzzy msgid "" "In Python, variables that are only referenced inside a function are " "implicitly global. If a variable is assigned a value anywhere within the " "function's body, it's assumed to be a local unless explicitly declared as " "global." msgstr "" "在 Python 中,僅在函式內部參照的變數是隱式全域變數。如果一個變數在函式體內的" "任何地方被賦值,除非明確聲明為全域變數,否則它被假定為局部變數。" #: ../../faq/programming.rst:198 #, fuzzy msgid "" "Though a bit surprising at first, a moment's consideration explains this. " "On one hand, requiring :keyword:`global` for assigned variables provides a " "bar against unintended side-effects. On the other hand, if ``global`` was " "required for all global references, you'd be using ``global`` all the time. " "You'd have to declare as global every reference to a built-in function or to " "a component of an imported module. This clutter would defeat the usefulness " "of the ``global`` declaration for identifying side-effects." msgstr "" "雖然起初有點令人驚訝,但稍加考慮就可以解釋這一點。一方面,要求 :keyword:" "`global` 分配的變數可以防止意外的副作用。另一方面,如果所有全域參照都需要 " "``global``,那麼你將一直使用 ``global``。你必須將對內建函式或引入模組的組件的" "每個參照聲明為全域。這種混亂會破壞用於識別副作用的 ``global`` 聲明的有用性。" #: ../../faq/programming.rst:208 #, fuzzy msgid "" "Why do lambdas defined in a loop with different values all return the same " "result?" msgstr "為什麼在具有不同值的循環中定義的 lambda 都回傳相同的結果?" #: ../../faq/programming.rst:210 msgid "" "Assume you use a for loop to define a few different lambdas (or even plain " "functions), e.g.::" msgstr "" "假設你使用 for 循環來定義幾個不同的 lambda(甚至是普通函式),例如: ::" #: ../../faq/programming.rst:213 msgid "" ">>> squares = []\n" ">>> for x in range(5):\n" "... squares.append(lambda: x**2)" msgstr "" ">>> squares = []\n" ">>> for x in range(5):\n" "... squares.append(lambda: x**2)" #: ../../faq/programming.rst:217 #, fuzzy msgid "" "This gives you a list that contains 5 lambdas that calculate ``x**2``. You " "might expect that, when called, they would return, respectively, ``0``, " "``1``, ``4``, ``9``, and ``16``. However, when you actually try you will " "see that they all return ``16``::" msgstr "" "這為你提供了一個包含 5 個計算 ``x**2`` 的 lambda 的list。你可能期望,當被呼叫" "時,它們會分別回傳 ``0``、``1``、``4``、``9`` 和 ``16``。然而,當你實際嘗試" "時,你會發現它們都回傳 ``16``: ::" #: ../../faq/programming.rst:222 msgid "" ">>> squares[2]()\n" "16\n" ">>> squares[4]()\n" "16" msgstr "" ">>> squares[2]()\n" "16\n" ">>> squares[4]()\n" "16" #: ../../faq/programming.rst:227 #, fuzzy msgid "" "This happens because ``x`` is not local to the lambdas, but is defined in " "the outer scope, and it is accessed when the lambda is called --- not when " "it is defined. At the end of the loop, the value of ``x`` is ``4``, so all " "the functions now return ``4**2``, i.e. ``16``. You can also verify this by " "changing the value of ``x`` and see how the results of the lambdas change::" msgstr "" "發生這種情況是因為 ``x`` 不是 lambda 的局部變數,而是在外部作用域中定義的,並" "且在呼叫 lambda 時存取它——而不是在定義時存取它。在循環結束時,``x`` 的值為 " "``4``,因此所有函式現在都回傳 ``4**2``,即 ``16``。你還可以透過更改 ``x`` 的" "值來驗證這一點,並查看 lambda 運算式的結果如何變化: ::" #: ../../faq/programming.rst:233 msgid "" ">>> x = 8\n" ">>> squares[2]()\n" "64" msgstr "" ">>> x = 8\n" ">>> squares[2]()\n" "64" #: ../../faq/programming.rst:237 #, fuzzy msgid "" "In order to avoid this, you need to save the values in variables local to " "the lambdas, so that they don't rely on the value of the global ``x``::" msgstr "" "為了避免這種情況,你需要將值保存在 lambda 的局部變數中,這樣它們就不會依賴於" "全域 ``x`` 的值: ::" #: ../../faq/programming.rst:240 msgid "" ">>> squares = []\n" ">>> for x in range(5):\n" "... squares.append(lambda n=x: n**2)" msgstr "" ">>> squares = []\n" ">>> for x in range(5):\n" "... squares.append(lambda n=x: n**2)" #: ../../faq/programming.rst:244 #, fuzzy msgid "" "Here, ``n=x`` creates a new variable ``n`` local to the lambda and computed " "when the lambda is defined so that it has the same value that ``x`` had at " "that point in the loop. This means that the value of ``n`` will be ``0`` in " "the first lambda, ``1`` in the second, ``2`` in the third, and so on. " "Therefore each lambda will now return the correct result::" msgstr "" "在這裡,``n=x`` 建立了一個新變數 ``n`` 局部於 lambda 並在定義 lambda 時計算," "因此它具有與 ``x`` 在循環中的那個點相同的值。這意味著 ``n`` 的值在第一個 " "lambda 中為 ``0`` ,在第二個中為 ``1`` ,在第三個中為 ``2`` ,依此類推。因此" "每個 lambda 現在將回傳正確的結果: ::" #: ../../faq/programming.rst:250 msgid "" ">>> squares[2]()\n" "4\n" ">>> squares[4]()\n" "16" msgstr "" ">>> squares[2]()\n" "4\n" ">>> squares[4]()\n" "16" #: ../../faq/programming.rst:255 msgid "" "Note that this behaviour is not peculiar to lambdas, but applies to regular " "functions too." msgstr "請注意,此行為並非 lambda 所特有,也適用於常規函式。" #: ../../faq/programming.rst:260 msgid "How do I share global variables across modules?" msgstr "如何跨模組共享全域變數?" #: ../../faq/programming.rst:262 #, fuzzy msgid "" "The canonical way to share information across modules within a single " "program is to create a special module (often called config or cfg). Just " "import the config module in all modules of your application; the module then " "becomes available as a global name. Because there is only one instance of " "each module, any changes made to the module object get reflected " "everywhere. For example:" msgstr "" "在單個程式中跨模組共享資訊的規範方法是建立一個特殊模組(通常稱為 config 或 " "cfg)。只需在應用程式的所有模組中引入配置模組;然後該模組可作為全域名稱使用。" "因為每個模組只有一個實例,所以對模組物件所做的任何更改都會在各處反映出來。例" "如:" #: ../../faq/programming.rst:268 msgid "config.py::" msgstr "config.py: ::" #: ../../faq/programming.rst:270 msgid "x = 0 # Default value of the 'x' configuration setting" msgstr "" #: ../../faq/programming.rst:272 msgid "mod.py::" msgstr "mod.py: ::" #: ../../faq/programming.rst:274 msgid "" "import config\n" "config.x = 1" msgstr "" "import config\n" "config.x = 1" #: ../../faq/programming.rst:277 msgid "main.py::" msgstr "main.py: ::" #: ../../faq/programming.rst:279 msgid "" "import config\n" "import mod\n" "print(config.x)" msgstr "" "import config\n" "import mod\n" "print(config.x)" #: ../../faq/programming.rst:283 #, fuzzy msgid "" "Note that using a module is also the basis for implementing the singleton " "design pattern, for the same reason." msgstr "請注意,出於同樣的原因,使用模組也是實作單例設計模式的基礎。" #: ../../faq/programming.rst:288 #, fuzzy msgid "What are the \"best practices\" for using import in a module?" msgstr "在模組中使用 import 的「最佳實踐」是什麼?" #: ../../faq/programming.rst:290 #, fuzzy msgid "" "In general, don't use ``from modulename import *``. Doing so clutters the " "importer's namespace, and makes it much harder for linters to detect " "undefined names." msgstr "" "一般來說,不要使用``from modulename import *``。這樣做會使引入器的命名空間混" "亂,並使 linters 更難檢測未定義的名稱。" #: ../../faq/programming.rst:294 #, fuzzy msgid "" "Import modules at the top of a file. Doing so makes it clear what other " "modules your code requires and avoids questions of whether the module name " "is in scope. Using one import per line makes it easy to add and delete " "module imports, but using multiple imports per line uses less screen space." msgstr "" "在檔案頂部引入模組。這樣做可以明確你的程式碼需要哪些其他模組,並避免模組名稱" "是否在範圍內的問題。每行使用一個引入可以輕鬆新增和刪除模組引入,但每行使用多" "個引入會佔用更少的屏幕空間。" #: ../../faq/programming.rst:299 #, fuzzy msgid "It's good practice if you import modules in the following order:" msgstr "如果你按以下順序引入模組,這是一個很好的做法:" #: ../../faq/programming.rst:301 msgid "" "standard library modules -- e.g. :mod:`sys`, :mod:`os`, :mod:`argparse`, :" "mod:`re`" msgstr "" "標準函式庫模組 —— 例如 :mod:`sys`、:mod:`os`、:mod:`argparse`、:mod:`re`" #: ../../faq/programming.rst:302 #, fuzzy msgid "" "third-party library modules (anything installed in Python's site-packages " "directory) -- e.g. :mod:`!dateutil`, :mod:`!requests`, :mod:`!PIL.Image`" msgstr "" "第三方函式庫模組(任何安裝在 Python 的站點包目錄中的模組)——例如:mod:`!" "dateutil`, :mod:`!requests`, :mod:`!PIL.Image`" #: ../../faq/programming.rst:304 #, fuzzy msgid "locally developed modules" msgstr "本地開發的模組" #: ../../faq/programming.rst:306 #, fuzzy msgid "" "It is sometimes necessary to move imports to a function or class to avoid " "problems with circular imports. Gordon McMillan says:" msgstr "有時需要將引入移動到函式或類別以避免循環引入的問題。戈登麥克米蘭 說:" #: ../../faq/programming.rst:309 #, fuzzy msgid "" "Circular imports are fine where both modules use the \"import \" " "form of import. They fail when the 2nd module wants to grab a name out of " "the first (\"from module import name\") and the import is at the top level. " "That's because names in the 1st are not yet available, because the first " "module is busy importing the 2nd." msgstr "" "在兩個模組都使用 \"import \" 引入形式的情況下,循環引入很好。當第二個" "模組想要從第一個模組中獲取一個名稱( \"from module import name\" )並且引入位" "於頂層時,它們會失敗。那是因為 1st 中的名稱尚不可用,因為第一個模組正忙於導" "入 2nd。" #: ../../faq/programming.rst:315 #, fuzzy msgid "" "In this case, if the second module is only used in one function, then the " "import can easily be moved into that function. By the time the import is " "called, the first module will have finished initializing, and the second " "module can do its import." msgstr "" "在這種情況下,如果第二個模組只在一個函式中使用,那麼引入可以很容易地移到那個" "函式中。在呼叫引入時,第一個模組將完成初始化,第二個模組可以進行引入。" #: ../../faq/programming.rst:320 #, fuzzy msgid "" "It may also be necessary to move imports out of the top level of code if " "some of the modules are platform-specific. In that case, it may not even be " "possible to import all of the modules at the top of the file. In this case, " "importing the correct modules in the corresponding platform-specific code is " "a good option." msgstr "" "如果某些模組是特定於平台的,則可能還需要將引入移出程式碼的頂層。在這種情況" "下,甚至可能無法引入檔案頂部的所有模組。在這種情況下,在相應的特定於平台的程" "式碼中引入正確的模組是一個不錯的選擇。" #: ../../faq/programming.rst:325 #, fuzzy msgid "" "Only move imports into a local scope, such as inside a function definition, " "if it's necessary to solve a problem such as avoiding a circular import or " "are trying to reduce the initialization time of a module. This technique is " "especially helpful if many of the imports are unnecessary depending on how " "the program executes. You may also want to move imports into a function if " "the modules are only ever used in that function. Note that loading a module " "the first time may be expensive because of the one time initialization of " "the module, but loading a module multiple times is virtually free, costing " "only a couple of dictionary lookups. Even if the module name has gone out " "of scope, the module is probably available in :data:`sys.modules`." msgstr "" "如果有必要解決諸如避免循環引入之類的問題或試圖減少模組的初始化時間,則僅將導" "入移動到局部範圍內,例如在函式定義內。如果根據程式的執行方式,許多引入是不必" "要的,則此技術特別有用。如果模組僅在該函式中使用,你可能還想將引入移動到該函" "式中。請注意,由於模組的一次性初始化,第一次載入模組可能很昂貴,但多次載入模" "組實際上是免費的,只需幾次字典查詢。即使模組名稱超出範圍,該模組也可能在 :" "data:`sys.modules` 中可用。" #: ../../faq/programming.rst:338 #, fuzzy msgid "Why are default values shared between objects?" msgstr "為什麼物件之間共享預設值?" #: ../../faq/programming.rst:340 #, fuzzy msgid "" "This type of bug commonly bites neophyte programmers. Consider this " "function::" msgstr "這種型別的錯誤通常會困擾新手程式員。考慮這個功能: ::" #: ../../faq/programming.rst:342 msgid "" "def foo(mydict={}): # Danger: shared reference to one dict for all calls\n" " ... compute something ...\n" " mydict[key] = value\n" " return mydict" msgstr "" #: ../../faq/programming.rst:347 #, fuzzy msgid "" "The first time you call this function, ``mydict`` contains a single item. " "The second time, ``mydict`` contains two items because when ``foo()`` begins " "executing, ``mydict`` starts out with an item already in it." msgstr "" "第一次呼叫此函式時, ``mydict`` 包含一個項目。第二次,``mydict`` 包含兩個項" "目,因為當 ``foo()`` 開始執行時,``mydict`` 以其中已有的項目開始。" #: ../../faq/programming.rst:351 #, fuzzy msgid "" "It is often expected that a function call creates new objects for default " "values. This is not what happens. Default values are created exactly once, " "when the function is defined. If that object is changed, like the " "dictionary in this example, subsequent calls to the function will refer to " "this changed object." msgstr "" "通常期望函式呼叫為預設值建立新物件。這不是發生的事情。當定義函式時,預設值只" "建立一次。如果該物件發生更改,如本例中的字典,則對該函式的後續呼叫將參照該已" "更改的物件。" #: ../../faq/programming.rst:356 #, fuzzy msgid "" "By definition, immutable objects such as numbers, strings, tuples, and " "``None``, are safe from change. Changes to mutable objects such as " "dictionaries, lists, and class instances can lead to confusion." msgstr "" "根據定義,數字、字串、元組和 ``None`` 等不可變物件是安全的,不會發生變化。對" "字典、list和類別實例等可變物件的更改可能會導致混淆。" #: ../../faq/programming.rst:360 #, fuzzy msgid "" "Because of this feature, it is good programming practice to not use mutable " "objects as default values. Instead, use ``None`` as the default value and " "inside the function, check if the parameter is ``None`` and create a new " "list/dictionary/whatever if it is. For example, don't write::" msgstr "" "由於這個特性,不使用可變物件作為預設值是一個很好的編程習慣。相反,使用 " "``None`` 作為預設值並在函式內部檢查參數是否為 ``None`` 並建立一個新的list/字" "典/無論是否是。例如,不要寫: ::" #: ../../faq/programming.rst:365 msgid "" "def foo(mydict={}):\n" " ..." msgstr "" "def foo(mydict={}):\n" " ..." #: ../../faq/programming.rst:368 msgid "but::" msgstr "但是: ::" #: ../../faq/programming.rst:370 msgid "" "def foo(mydict=None):\n" " if mydict is None:\n" " mydict = {} # create a new dict for local namespace" msgstr "" #: ../../faq/programming.rst:374 #, fuzzy msgid "" "This feature can be useful. When you have a function that's time-consuming " "to compute, a common technique is to cache the parameters and the resulting " "value of each call to the function, and return the cached value if the same " "value is requested again. This is called \"memoizing\", and can be " "implemented like this::" msgstr "" "此功能可能很有用。當你有一個計算起來很耗時的函式時,一種常用的技術是快取參數" "和每次呼叫該函式的結果值,並在再次請求相同的值時回傳快取的值。這稱為「記憶" "化」,可以像這樣實作: ::" #: ../../faq/programming.rst:379 msgid "" "# Callers can only provide two parameters and optionally pass _cache by " "keyword\n" "def expensive(arg1, arg2, *, _cache={}):\n" " if (arg1, arg2) in _cache:\n" " return _cache[(arg1, arg2)]\n" "\n" " # Calculate the value\n" " result = ... expensive computation ...\n" " _cache[(arg1, arg2)] = result # Store result in the cache\n" " return result" msgstr "" #: ../../faq/programming.rst:389 #, fuzzy msgid "" "You could use a global variable containing a dictionary instead of the " "default value; it's a matter of taste." msgstr "你可以使用包含字典的全域變數而不是預設值;這是一個品味問題。" #: ../../faq/programming.rst:394 #, fuzzy msgid "" "How can I pass optional or keyword parameters from one function to another?" msgstr "如何將可選參數或關鍵字參數從一個函式傳遞到另一個函式?" #: ../../faq/programming.rst:396 #, fuzzy msgid "" "Collect the arguments using the ``*`` and ``**`` specifiers in the " "function's parameter list; this gives you the positional arguments as a " "tuple and the keyword arguments as a dictionary. You can then pass these " "arguments when calling another function by using ``*`` and ``**``::" msgstr "" "在函式的引數list中使用``*`` 和``**`` 說明符收集參數;這為你提供了作為元組的位" "置引數和作為字典的關鍵字引數。然後,你可以在使用 ``*`` 和 ``**`` 呼叫另一個函" "式時傳遞這些引數: ::" #: ../../faq/programming.rst:401 msgid "" "def f(x, *args, **kwargs):\n" " ...\n" " kwargs['width'] = '14.3c'\n" " ...\n" " g(x, *args, **kwargs)" msgstr "" "def f(x, *args, **kwargs):\n" " ...\n" " kwargs['width'] = '14.3c'\n" " ...\n" " g(x, *args, **kwargs)" #: ../../faq/programming.rst:415 msgid "What is the difference between arguments and parameters?" msgstr "引數 (arguments) 和參數 (parameters) 有什麼區別?" #: ../../faq/programming.rst:417 #, fuzzy msgid "" ":term:`Parameters ` are defined by the names that appear in a " "function definition, whereas :term:`arguments ` are the values " "actually passed to a function when calling it. Parameters define what :term:" "`kind of arguments ` a function can accept. For example, given " "the function definition::" msgstr "" ":term:`參數 `\\ 由出現在函式定義中的名稱定義,而\\ :term:`引數 " "`\\ 是呼叫函式時實際傳遞給函式的值。參數定義函式可以接受的\\ :term:" "引數種類 `。例如,給定函式定義: ::" #: ../../faq/programming.rst:423 msgid "" "def func(foo, bar=None, **kwargs):\n" " pass" msgstr "" "def func(foo, bar=None, **kwargs):\n" " pass" #: ../../faq/programming.rst:426 msgid "" "*foo*, *bar* and *kwargs* are parameters of ``func``. However, when calling " "``func``, for example::" msgstr "" "*foo*、*bar* 和 *kwargs* 是 ``func`` 的參數。然而,當呼叫 ``func`` 時,例" "如: ::" #: ../../faq/programming.rst:429 msgid "func(42, bar=314, extra=somevar)" msgstr "func(42, bar=314, extra=somevar)" #: ../../faq/programming.rst:431 msgid "the values ``42``, ``314``, and ``somevar`` are arguments." msgstr "``42`` 、 ``314`` 和 ``somevar`` 是引數。" #: ../../faq/programming.rst:435 msgid "Why did changing list 'y' also change list 'x'?" msgstr "為什麼更改 list 'y' 也會更改 list 'x'?" #: ../../faq/programming.rst:437 msgid "If you wrote code like::" msgstr "如果你寫了像這樣的程式碼: ::" #: ../../faq/programming.rst:439 msgid "" ">>> x = []\n" ">>> y = x\n" ">>> y.append(10)\n" ">>> y\n" "[10]\n" ">>> x\n" "[10]" msgstr "" ">>> x = []\n" ">>> y = x\n" ">>> y.append(10)\n" ">>> y\n" "[10]\n" ">>> x\n" "[10]" #: ../../faq/programming.rst:447 msgid "" "you might be wondering why appending an element to ``y`` changed ``x`` too." msgstr "你可能想知道為什麼將一個元素附加到 ``y`` 時也會改變 ``x``。" #: ../../faq/programming.rst:449 msgid "There are two factors that produce this result:" msgstr "產生這個結果的原因有兩個:" #: ../../faq/programming.rst:451 #, fuzzy msgid "" "Variables are simply names that refer to objects. Doing ``y = x`` doesn't " "create a copy of the list -- it creates a new variable ``y`` that refers to " "the same object ``x`` refers to. This means that there is only one object " "(the list), and both ``x`` and ``y`` refer to it." msgstr "" "變數只是參照物件的名稱。執行 ``y = x`` 不會建立list的副本——它會建立一個新變" "數 ``y``,它指向 ``x`` 指向的同一物件。這意味著只有一個物件(list),並且 " "``x`` 和 ``y`` 都參照它。" #: ../../faq/programming.rst:455 msgid "" "Lists are :term:`mutable`, which means that you can change their content." msgstr "list 是 :term:`mutable`,這意味著你可以變更它們的內容。" #: ../../faq/programming.rst:457 #, fuzzy msgid "" "After the call to :meth:`!append`, the content of the mutable object has " "changed from ``[]`` to ``[10]``. Since both the variables refer to the same " "object, using either name accesses the modified value ``[10]``." msgstr "" "在呼叫 :meth:`!append` 之後,可變物件的內容從 ``[]`` 變成了 ``[10]``。由於這" "兩個變數都參照同一個物件,因此使用任一名稱都可以存取修改後的值 ``[10]`` 。" #: ../../faq/programming.rst:461 #, fuzzy msgid "If we instead assign an immutable object to ``x``::" msgstr "如果我們改為將不可變物件分配給 ``x``: ::" #: ../../faq/programming.rst:463 msgid "" ">>> x = 5 # ints are immutable\n" ">>> y = x\n" ">>> x = x + 1 # 5 can't be mutated, we are creating a new object here\n" ">>> x\n" "6\n" ">>> y\n" "5" msgstr "" #: ../../faq/programming.rst:471 #, fuzzy msgid "" "we can see that in this case ``x`` and ``y`` are not equal anymore. This is " "because integers are :term:`immutable`, and when we do ``x = x + 1`` we are " "not mutating the int ``5`` by incrementing its value; instead, we are " "creating a new object (the int ``6``) and assigning it to ``x`` (that is, " "changing which object ``x`` refers to). After this assignment we have two " "objects (the ints ``6`` and ``5``) and two variables that refer to them " "(``x`` now refers to ``6`` but ``y`` still refers to ``5``)." msgstr "" "我們可以看到,在這種情況下,``x`` 和 ``y`` 不再相等。這是因為整數是不可變的," "當我們做 x = x + 1 時,我們並沒有透過增加它的值來改變 int 5 ;相反,我們正在" "建立一個新物件(int ``6``)並將其分配給``x``(也就是說,更改``x``指向的物" "件)。在這個賦值之後,我們有兩個物件(整數 ``6`` 和 ``5``)和兩個參照它們的變" "數(``x`` 現在指的是 ``6`` 但 ``y`` 仍然指的是``5``)。" #: ../../faq/programming.rst:479 #, fuzzy msgid "" "Some operations (for example ``y.append(10)`` and ``y.sort()``) mutate the " "object, whereas superficially similar operations (for example ``y = y + " "[10]`` and :func:`sorted(y) `) create a new object. In general in " "Python (and in all cases in the standard library) a method that mutates an " "object will return ``None`` to help avoid getting the two types of " "operations confused. So if you mistakenly write ``y.sort()`` thinking it " "will give you a sorted copy of ``y``, you'll instead end up with ``None``, " "which will likely cause your program to generate an easily diagnosed error." msgstr "" "一些操作(例如 ``y.append(10)`` 和 ``y.sort()``)會改變物件,而表面上相似的操" "作(例如 ``y = y + [10]`` 和: func:`sorted(y) `) 建立一個新物件。通" "常在 Python 中(以及在標準函式庫中的所有情況下)改變物件的方法將回傳 " "``None`` 以幫助避免混淆這兩種型別的操作。因此,如果你錯誤地編寫了 ``y." "sort()``,認為它會為你提供 ``y`` 的排序副本,那麼你最終會得到 ``None``,這可" "能會導致你的程式生成一個容易診斷的錯誤。" #: ../../faq/programming.rst:488 #, fuzzy msgid "" "However, there is one class of operations where the same operation sometimes " "has different behaviors with different types: the augmented assignment " "operators. For example, ``+=`` mutates lists but not tuples or ints " "(``a_list += [1, 2, 3]`` is equivalent to ``a_list.extend([1, 2, 3])`` and " "mutates ``a_list``, whereas ``some_tuple += (1, 2, 3)`` and ``some_int += " "1`` create new objects)." msgstr "" "但是,有一種操作,其中相同的操作有時具有不同型別的不同行為:擴充賦值運算子。" "例如,``+=`` 改變list而不是元組或整數(``a_list += [1, 2, 3]`` 等同於" "``a_list.extend([1, 2, 3])``並改變 ``a_list``,而 ``some_tuple += (1, 2, " "3)`` 和 ``some_int += 1`` 建立新物件)。" #: ../../faq/programming.rst:495 msgid "In other words:" msgstr "換句話說:" #: ../../faq/programming.rst:497 #, fuzzy msgid "" "If we have a mutable object (:class:`list`, :class:`dict`, :class:`set`, " "etc.), we can use some specific operations to mutate it and all the " "variables that refer to it will see the change." msgstr "" "如果我們有一個可變物件(:class:`list`、:class:`dict`、:class:`set` 等),我們" "可以使用一些特定的操作來改變它,所有參照它的變數都會看到變化。" #: ../../faq/programming.rst:500 #, fuzzy msgid "" "If we have an immutable object (:class:`str`, :class:`int`, :class:`tuple`, " "etc.), all the variables that refer to it will always see the same value, " "but operations that transform that value into a new value always return a " "new object." msgstr "" "如果我們有一個不可變物件(:class:`str`、:class:`int`、:class:`tuple` 等),所" "有參照它的變數將始終看到相同的值,但是轉換的操作將該值轉化為新值總是回傳一個" "新物件。" #: ../../faq/programming.rst:505 #, fuzzy msgid "" "If you want to know if two variables refer to the same object or not, you " "can use the :keyword:`is` operator, or the built-in function :func:`id`." msgstr "" "如果你想知道兩個變數是否參照同一個物件,你可以使用 :keyword:`is` 運算子,或內" "置函式 :func:`id`。" #: ../../faq/programming.rst:510 #, fuzzy msgid "How do I write a function with output parameters (call by reference)?" msgstr "如何編寫帶有輸出參數的函式(透過參照呼叫)?" #: ../../faq/programming.rst:512 #, fuzzy msgid "" "Remember that arguments are passed by assignment in Python. Since " "assignment just creates references to objects, there's no alias between an " "argument name in the caller and callee, and so no call-by-reference per se. " "You can achieve the desired effect in a number of ways." msgstr "" "請記住,在 Python 中引數是透過賦值傳遞的。由於賦值只是建立對物件的參照,因此" "呼叫者和被呼叫者的引數名稱之間沒有別名,因此本身沒有按參照呼叫。你可以透過多" "種方式實作所需的效果。" #: ../../faq/programming.rst:517 msgid "By returning a tuple of the results::" msgstr "透過回傳結果的元組: ::" #: ../../faq/programming.rst:519 msgid "" ">>> def func1(a, b):\n" "... a = 'new-value' # a and b are local names\n" "... b = b + 1 # assigned to new objects\n" "... return a, b # return new values\n" "...\n" ">>> x, y = 'old-value', 99\n" ">>> func1(x, y)\n" "('new-value', 100)" msgstr "" #: ../../faq/programming.rst:528 #, fuzzy msgid "This is almost always the clearest solution." msgstr "這幾乎總是最清晰的解決方案。" #: ../../faq/programming.rst:530 #, fuzzy msgid "" "By using global variables. This isn't thread-safe, and is not recommended." msgstr "透過使用全域變數。這不是執行緒安全的,不推薦。" #: ../../faq/programming.rst:532 #, fuzzy msgid "By passing a mutable (changeable in-place) object::" msgstr "透過傳遞一個可變的(原地可變的)物件: ::" #: ../../faq/programming.rst:534 msgid "" ">>> def func2(a):\n" "... a[0] = 'new-value' # 'a' references a mutable list\n" "... a[1] = a[1] + 1 # changes a shared object\n" "...\n" ">>> args = ['old-value', 99]\n" ">>> func2(args)\n" ">>> args\n" "['new-value', 100]" msgstr "" #: ../../faq/programming.rst:543 #, fuzzy msgid "By passing in a dictionary that gets mutated::" msgstr "透過傳入一個發生變異的字典: ::" #: ../../faq/programming.rst:545 msgid "" ">>> def func3(args):\n" "... args['a'] = 'new-value' # args is a mutable dictionary\n" "... args['b'] = args['b'] + 1 # change it in-place\n" "...\n" ">>> args = {'a': 'old-value', 'b': 99}\n" ">>> func3(args)\n" ">>> args\n" "{'a': 'new-value', 'b': 100}" msgstr "" #: ../../faq/programming.rst:554 #, fuzzy msgid "Or bundle up values in a class instance::" msgstr "或者在類別實例中捆綁值: ::" #: ../../faq/programming.rst:556 msgid "" ">>> class Namespace:\n" "... def __init__(self, /, **args):\n" "... for key, value in args.items():\n" "... setattr(self, key, value)\n" "...\n" ">>> def func4(args):\n" "... args.a = 'new-value' # args is a mutable Namespace\n" "... args.b = args.b + 1 # change object in-place\n" "...\n" ">>> args = Namespace(a='old-value', b=99)\n" ">>> func4(args)\n" ">>> vars(args)\n" "{'a': 'new-value', 'b': 100}" msgstr "" #: ../../faq/programming.rst:571 #, fuzzy msgid "There's almost never a good reason to get this complicated." msgstr "幾乎沒有充分的理由讓事情變得如此復雜。" #: ../../faq/programming.rst:573 #, fuzzy msgid "Your best choice is to return a tuple containing the multiple results." msgstr "你最好的選擇是回傳一個包含多個結果的元組。" #: ../../faq/programming.rst:577 #, fuzzy msgid "How do you make a higher order function in Python?" msgstr "你如何在 Python 中建立高階函式?" #: ../../faq/programming.rst:579 #, fuzzy msgid "" "You have two choices: you can use nested scopes or you can use callable " "objects. For example, suppose you wanted to define ``linear(a,b)`` which " "returns a function ``f(x)`` that computes the value ``a*x+b``. Using nested " "scopes::" msgstr "" "你有兩種選擇:可以使用巢狀作用域,也可以使用可呼叫物件。例如,假設你想定義 " "linear(a,b) ,它回傳一個計算值 a*x+b 的函式 f(x) 。使用嵌套範圍: ::" #: ../../faq/programming.rst:583 msgid "" "def linear(a, b):\n" " def result(x):\n" " return a * x + b\n" " return result" msgstr "" "def linear(a, b):\n" " def result(x):\n" " return a * x + b\n" " return result" #: ../../faq/programming.rst:588 msgid "Or using a callable object::" msgstr "或者使用可呼叫物件: ::" #: ../../faq/programming.rst:590 msgid "" "class linear:\n" "\n" " def __init__(self, a, b):\n" " self.a, self.b = a, b\n" "\n" " def __call__(self, x):\n" " return self.a * x + self.b" msgstr "" "class linear:\n" "\n" " def __init__(self, a, b):\n" " self.a, self.b = a, b\n" "\n" " def __call__(self, x):\n" " return self.a * x + self.b" #: ../../faq/programming.rst:598 #, fuzzy msgid "In both cases, ::" msgstr "在這兩種情況下: ::" #: ../../faq/programming.rst:600 msgid "taxes = linear(0.3, 2)" msgstr "taxes = linear(0.3, 2)" #: ../../faq/programming.rst:602 #, fuzzy msgid "gives a callable object where ``taxes(10e6) == 0.3 * 10e6 + 2``." msgstr "給出一個可呼叫物件,其中 ``taxes(10e6) == 0.3 * 10e6 + 2``。" #: ../../faq/programming.rst:604 #, fuzzy msgid "" "The callable object approach has the disadvantage that it is a bit slower " "and results in slightly longer code. However, note that a collection of " "callables can share their signature via inheritance::" msgstr "" "可呼叫物件方法的缺點是它有點慢並且導致程式碼稍長。但是,請注意,可呼叫集合可" "以透過繼承共享它們的簽名: ::" #: ../../faq/programming.rst:608 msgid "" "class exponential(linear):\n" " # __init__ inherited\n" " def __call__(self, x):\n" " return self.a * (x ** self.b)" msgstr "" "class exponential(linear):\n" " # __init__ inherited\n" " def __call__(self, x):\n" " return self.a * (x ** self.b)" #: ../../faq/programming.rst:613 msgid "Object can encapsulate state for several methods::" msgstr "物件可以封裝多個方法的狀態: ::" #: ../../faq/programming.rst:615 msgid "" "class counter:\n" "\n" " value = 0\n" "\n" " def set(self, x):\n" " self.value = x\n" "\n" " def up(self):\n" " self.value = self.value + 1\n" "\n" " def down(self):\n" " self.value = self.value - 1\n" "\n" "count = counter()\n" "inc, dec, reset = count.up, count.down, count.set" msgstr "" "class counter:\n" "\n" " value = 0\n" "\n" " def set(self, x):\n" " self.value = x\n" "\n" " def up(self):\n" " self.value = self.value + 1\n" "\n" " def down(self):\n" " self.value = self.value - 1\n" "\n" "count = counter()\n" "inc, dec, reset = count.up, count.down, count.set" #: ../../faq/programming.rst:631 msgid "" "Here ``inc()``, ``dec()`` and ``reset()`` act like functions which share the " "same counting variable." msgstr "" "這裡的 ``inc()``、``dec()`` 和 ``reset()`` 就像共享相同計數變數的函式一樣。" #: ../../faq/programming.rst:636 msgid "How do I copy an object in Python?" msgstr "如何在 Python 中複製物件?" #: ../../faq/programming.rst:638 #, fuzzy msgid "" "In general, try :func:`copy.copy` or :func:`copy.deepcopy` for the general " "case. Not all objects can be copied, but most can." msgstr "" "一般來說,對於一般情況,請嘗試 :func:`copy.copy` 或 :func:`copy.deepcopy`。並" "非所有物件都可以複製,但大多數都可以。" #: ../../faq/programming.rst:641 #, fuzzy msgid "" "Some objects can be copied more easily. Dictionaries have a :meth:`~dict." "copy` method::" msgstr "可以更輕鬆地複製某些物件。字典有一個 :meth:`~dict.copy` 方法: ::" #: ../../faq/programming.rst:644 msgid "newdict = olddict.copy()" msgstr "newdict = olddict.copy()" #: ../../faq/programming.rst:646 msgid "Sequences can be copied by slicing::" msgstr "序列可以透過切片 (slicing) 複製: ::" #: ../../faq/programming.rst:648 msgid "new_l = l[:]" msgstr "new_l = l[:]" #: ../../faq/programming.rst:652 msgid "How can I find the methods or attributes of an object?" msgstr "如何找到物件的方法或屬性?" #: ../../faq/programming.rst:654 #, fuzzy msgid "" "For an instance ``x`` of a user-defined class, :func:`dir(x) ` returns " "an alphabetized list of the names containing the instance attributes and " "methods and attributes defined by its class." msgstr "" "對於使用者定義類別的實例 ``x``,:func:`dir(x) ` 回傳一個按字母順序排列的" "名稱list,其中包含其類別定義的實例屬性、方法和屬性。" #: ../../faq/programming.rst:660 msgid "How can my code discover the name of an object?" msgstr "我的程式碼如何發現物件的名稱?" #: ../../faq/programming.rst:662 #, fuzzy msgid "" "Generally speaking, it can't, because objects don't really have names. " "Essentially, assignment always binds a name to a value; the same is true of " "``def`` and ``class`` statements, but in that case the value is a callable. " "Consider the following code::" msgstr "" "一般來說,它不能,因為物件並沒有真正的名字。本質上,賦值總是將名稱綁定到值; " "``def`` 和 ``class`` 陳述式也是如此,但在那種情況下,值是可呼叫的。考慮以下程" "式碼: ::" #: ../../faq/programming.rst:667 msgid "" ">>> class A:\n" "... pass\n" "...\n" ">>> B = A\n" ">>> a = B()\n" ">>> b = a\n" ">>> print(b)\n" "<__main__.A object at 0x16D07CC>\n" ">>> print(a)\n" "<__main__.A object at 0x16D07CC>" msgstr "" ">>> class A:\n" "... pass\n" "...\n" ">>> B = A\n" ">>> a = B()\n" ">>> b = a\n" ">>> print(b)\n" "<__main__.A object at 0x16D07CC>\n" ">>> print(a)\n" "<__main__.A object at 0x16D07CC>" #: ../../faq/programming.rst:678 #, fuzzy msgid "" "Arguably the class has a name: even though it is bound to two names and " "invoked through the name ``B`` the created instance is still reported as an " "instance of class ``A``. However, it is impossible to say whether the " "instance's name is ``a`` or ``b``, since both names are bound to the same " "value." msgstr "" "可以說該類別有一個名稱:即使它綁定到兩個名稱並透過名稱 ``B`` 呼叫,建立的實例" "仍然被報告為類別 ``A`` 的實例。但是,無法確定實例的名稱是 ``a`` 還是 ``b`` ," "因為這兩個名稱都綁定到相同的值。" #: ../../faq/programming.rst:683 #, fuzzy msgid "" "Generally speaking it should not be necessary for your code to \"know the " "names\" of particular values. Unless you are deliberately writing " "introspective programs, this is usually an indication that a change of " "approach might be beneficial." msgstr "" "一般來說,你的程式碼不必「知道特定值的名稱」。除非你有意編寫內省程式,否則這" "通常表明改變方法可能是有益的。" #: ../../faq/programming.rst:688 msgid "" "In comp.lang.python, Fredrik Lundh once gave an excellent analogy in answer " "to this question:" msgstr "" "在 comp.lang.python 中,Fredrik Lundh 曾針對這個問題給出了一個極好的比喻:" #: ../../faq/programming.rst:691 msgid "" "The same way as you get the name of that cat you found on your porch: the " "cat (object) itself cannot tell you its name, and it doesn't really care -- " "so the only way to find out what it's called is to ask all your neighbours " "(namespaces) if it's their cat (object)..." msgstr "" "就像你在門廊上發現的那隻貓的名字一樣:貓(物件)本身不能告訴你它的名字,它也" "不關心 - 所以找出它叫什麼的唯一方法是詢問所有鄰居(命名空間)是否是他們的貓" "(物件)..." #: ../../faq/programming.rst:696 msgid "" "....and don't be surprised if you'll find that it's known by many names, or " "no name at all!" msgstr "....如果你發現它有很多名字,或者根本沒有名字,請不要感到驚訝!" #: ../../faq/programming.rst:701 #, fuzzy msgid "What's up with the comma operator's precedence?" msgstr "逗號運算子的優先級是怎麼回事?" #: ../../faq/programming.rst:703 #, fuzzy msgid "Comma is not an operator in Python. Consider this session::" msgstr "逗號不是 Python 中的運算子。考慮這個會話: ::" #: ../../faq/programming.rst:705 msgid "" ">>> \"a\" in \"b\", \"a\"\n" "(False, 'a')" msgstr "" ">>> \"a\" in \"b\", \"a\"\n" "(False, 'a')" #: ../../faq/programming.rst:708 #, fuzzy msgid "" "Since the comma is not an operator, but a separator between expressions the " "above is evaluated as if you had entered::" msgstr "" "由於逗號不是運算子,而是運算式之間的分隔符,因此上面的計算就像你輸入的那" "樣: ::" #: ../../faq/programming.rst:711 msgid "(\"a\" in \"b\"), \"a\"" msgstr "(\"a\" in \"b\"), \"a\"" #: ../../faq/programming.rst:713 msgid "not::" msgstr "而不是: ::" #: ../../faq/programming.rst:715 msgid "\"a\" in (\"b\", \"a\")" msgstr "\"a\" in (\"b\", \"a\")" #: ../../faq/programming.rst:717 #, fuzzy msgid "" "The same is true of the various assignment operators (``=``, ``+=`` etc). " "They are not truly operators but syntactic delimiters in assignment " "statements." msgstr "" "各種賦值運算子(``=``、``+=`` 等)也是如此。它們不是真正的運算子,而是賦值語" "句中的句法定界符。" #: ../../faq/programming.rst:722 msgid "Is there an equivalent of C's \"?:\" ternary operator?" msgstr "是否有等效於 C 的 \"?:\" 三元運算子?" #: ../../faq/programming.rst:724 msgid "Yes, there is. The syntax is as follows::" msgstr "有的,語法如下: ::" #: ../../faq/programming.rst:726 msgid "" "[on_true] if [expression] else [on_false]\n" "\n" "x, y = 50, 25\n" "small = x if x < y else y" msgstr "" "[on_true] if [expression] else [on_false]\n" "\n" "x, y = 50, 25\n" "small = x if x < y else y" #: ../../faq/programming.rst:731 #, fuzzy msgid "" "Before this syntax was introduced in Python 2.5, a common idiom was to use " "logical operators::" msgstr "" "在 Python 2.5 中引入此語法之前,一個常見的習慣用法是使用邏輯運算子: ::" #: ../../faq/programming.rst:734 msgid "[expression] and [on_true] or [on_false]" msgstr "[expression] and [on_true] or [on_false]" #: ../../faq/programming.rst:736 #, fuzzy msgid "" "However, this idiom is unsafe, as it can give wrong results when *on_true* " "has a false boolean value. Therefore, it is always better to use the ``... " "if ... else ...`` form." msgstr "" "然而,這個慣用語是不安全的,因為當 *on_true* 有一個錯誤的布林值時它會給出錯誤" "的結果。因此,最好使用 ``... if ... else ...`` 形式。" #: ../../faq/programming.rst:742 #, fuzzy msgid "Is it possible to write obfuscated one-liners in Python?" msgstr "是否可以在 Python 中編寫混淆的單行程式碼?" #: ../../faq/programming.rst:744 #, fuzzy msgid "" "Yes. Usually this is done by nesting :keyword:`lambda` within :keyword:`!" "lambda`. See the following three examples, slightly adapted from Ulf " "Bartelt::" msgstr "" "是的。通常這是透過在 :keyword:`!lambda` 中嵌套 :keyword:`lambda` 來完成的。請" "參閱以下三個示例,稍微改編自 Ulf Bartelt: ::" #: ../../faq/programming.rst:747 msgid "" "from functools import reduce\n" "\n" "# Primes < 1000\n" "print(list(filter(None,map(lambda y:y*reduce(lambda x,y:x*y!=0,\n" "map(lambda x,y=y:y%x,range(2,int(pow(y,0.5)+1))),1),range(2,1000)))))\n" "\n" "# First 10 Fibonacci numbers\n" "print(list(map(lambda x,f=lambda x,f:(f(x-1,f)+f(x-2,f)) if x>1 else 1:\n" "f(x,f), range(10))))\n" "\n" "# Mandelbrot set\n" "print((lambda Ru,Ro,Iu,Io,IM,Sx,Sy:reduce(lambda x,y:x+'\\n'+y,map(lambda " "y,\n" "Iu=Iu,Io=Io,Ru=Ru,Ro=Ro,Sy=Sy,L=lambda yc,Iu=Iu,Io=Io,Ru=Ru,Ro=Ro,i=IM,\n" "Sx=Sx,Sy=Sy:reduce(lambda x,y:x+y,map(lambda x,xc=Ru,yc=yc,Ru=Ru,Ro=Ro,\n" "i=i,Sx=Sx,F=lambda xc,yc,x,y,k,f=lambda xc,yc,x,y,k,f:(k<=0)or (x*x+y*y\n" ">=4.0) or 1+f(xc,yc,x*x-y*y+xc,2.0*x*y+yc,k-1,f):f(xc,yc,x,y,k,f):chr(\n" "64+F(Ru+x*(Ro-Ru)/Sx,yc,0,0,i)),range(Sx))):L(Iu+y*(Io-Iu)/Sy),range(Sy\n" "))))(-2.1, 0.7, -1.2, 1.2, 30, 80, 24))\n" "# \\___ ___/ \\___ ___/ | | |__ lines on screen\n" "# V V | |______ columns on screen\n" "# | | |__________ maximum of \"iterations\"\n" "# | |_________________ range on y axis\n" "# |____________________________ range on x axis" msgstr "" #: ../../faq/programming.rst:771 msgid "Don't try this at home, kids!" msgstr "孩子們,不要在家裡嘗試這個!" #: ../../faq/programming.rst:777 #, fuzzy msgid "What does the slash(/) in the parameter list of a function mean?" msgstr "函式參數 list 中的斜槓(/)是什麼意思?" #: ../../faq/programming.rst:779 #, fuzzy msgid "" "A slash in the argument list of a function denotes that the parameters prior " "to it are positional-only. Positional-only parameters are the ones without " "an externally usable name. Upon calling a function that accepts positional-" "only parameters, arguments are mapped to parameters based solely on their " "position. For example, :func:`divmod` is a function that accepts positional-" "only parameters. Its documentation looks like this::" msgstr "" "函式引數list中的斜杠表示它前面的參數是位置參數。僅位置參數是沒有外部可用名稱" "的參數。在呼叫接受僅位置參數的函式時,參數僅根據其位置映射到參數。例如,:" "func:`divmod` 是一個只接受位置參數的函式。它的文件看起來像這樣: ::" #: ../../faq/programming.rst:786 msgid "" ">>> help(divmod)\n" "Help on built-in function divmod in module builtins:\n" "\n" "divmod(x, y, /)\n" " Return the tuple (x//y, x%y). Invariant: div*y + mod == x." msgstr "" ">>> help(divmod)\n" "Help on built-in function divmod in module builtins:\n" "\n" "divmod(x, y, /)\n" " Return the tuple (x//y, x%y). Invariant: div*y + mod == x." #: ../../faq/programming.rst:792 #, fuzzy msgid "" "The slash at the end of the parameter list means that both parameters are " "positional-only. Thus, calling :func:`divmod` with keyword arguments would " "lead to an error::" msgstr "" "參數list末尾的斜杠表示兩個參數都是位置參數。因此,使用關鍵字引數呼叫 :func:" "`divmod` 會導致錯誤: ::" #: ../../faq/programming.rst:796 msgid "" ">>> divmod(x=3, y=4)\n" "Traceback (most recent call last):\n" " File \"\", line 1, in \n" "TypeError: divmod() takes no keyword arguments" msgstr "" ">>> divmod(x=3, y=4)\n" "Traceback (most recent call last):\n" " File \"\", line 1, in \n" "TypeError: divmod() takes no keyword arguments" #: ../../faq/programming.rst:803 msgid "Numbers and strings" msgstr "數字和字串" #: ../../faq/programming.rst:806 msgid "How do I specify hexadecimal and octal integers?" msgstr "如何指定十六進位和八進位整數?" #: ../../faq/programming.rst:808 #, fuzzy msgid "" "To specify an octal digit, precede the octal value with a zero, and then a " "lower or uppercase \"o\". For example, to set the variable \"a\" to the " "octal value \"10\" (8 in decimal), type::" msgstr "" "要指定八進位數字,請在八進位值前面加上零,然後是小寫或大寫的 \"o\" 。例如,要" "將變數 \"a\" 設定為八進位值 \"10\" (十進位為 8),請鍵入: ::" #: ../../faq/programming.rst:812 msgid "" ">>> a = 0o10\n" ">>> a\n" "8" msgstr "" ">>> a = 0o10\n" ">>> a\n" "8" #: ../../faq/programming.rst:816 #, fuzzy msgid "" "Hexadecimal is just as easy. Simply precede the hexadecimal number with a " "zero, and then a lower or uppercase \"x\". Hexadecimal digits can be " "specified in lower or uppercase. For example, in the Python interpreter::" msgstr "" "十六進位也很容易。只需在十六進位數前面加上一個零,然後是一個小寫或大寫的 " "\"x\" 。可以用小寫或大寫形式指定十六進位數字。例如,在 Python 直譯器中: ::" #: ../../faq/programming.rst:820 msgid "" ">>> a = 0xa5\n" ">>> a\n" "165\n" ">>> b = 0XB2\n" ">>> b\n" "178" msgstr "" ">>> a = 0xa5\n" ">>> a\n" "165\n" ">>> b = 0XB2\n" ">>> b\n" "178" #: ../../faq/programming.rst:829 msgid "Why does -22 // 10 return -3?" msgstr "為什麼 -22 // 10 回傳 -3?" #: ../../faq/programming.rst:831 #, fuzzy msgid "" "It's primarily driven by the desire that ``i % j`` have the same sign as " "``j``. If you want that, and also want::" msgstr "" "它主要是由希望 ``i % j`` 與 ``j`` 具有相同的符號驅動的。如果你想要那個,也想" "要: ::" #: ../../faq/programming.rst:834 msgid "i == (i // j) * j + (i % j)" msgstr "i == (i // j) * j + (i % j)" #: ../../faq/programming.rst:836 msgid "" "then integer division has to return the floor. C also requires that " "identity to hold, and then compilers that truncate ``i // j`` need to make " "``i % j`` have the same sign as ``i``." msgstr "" "那麼整數除法必須回傳向下取整的結果。 C 還要求保留​​該識別性,然後截斷 ``i // " "j`` 的編譯器需要使 ``i % j`` 具有與 ``i`` 相同的符號。" #: ../../faq/programming.rst:840 #, fuzzy msgid "" "There are few real use cases for ``i % j`` when ``j`` is negative. When " "``j`` is positive, there are many, and in virtually all of them it's more " "useful for ``i % j`` to be ``>= 0``. If the clock says 10 now, what did it " "say 200 hours ago? ``-190 % 12 == 2`` is useful; ``-190 % 12 == -10`` is a " "bug waiting to bite." msgstr "" "當 j 為負時,i % j 的實際用例很少。當 ``j`` 為正時,有很多,並且在幾乎所有情" "況下,``i % j`` 為 ``>= 0`` 更有用。如果時鐘現在是 10 點,那麼 200 小時前它是" "什麼? ``-190 % 12 == 2`` 很有用; ``-190 % 12 == -10`` 是一個等著咬人的錯" "誤。" #: ../../faq/programming.rst:848 #, fuzzy msgid "How do I get int literal attribute instead of SyntaxError?" msgstr "如何取得 int 文字屬性而不是 SyntaxError?" #: ../../faq/programming.rst:850 #, fuzzy msgid "" "Trying to lookup an ``int`` literal attribute in the normal manner gives a :" "exc:`SyntaxError` because the period is seen as a decimal point::" msgstr "" "嘗試以正常方式查詢 ``int`` 文字屬性會給出一個 SyntaxError ,因為句點被視為小" "數點: ::" #: ../../faq/programming.rst:853 msgid "" ">>> 1.__class__\n" " File \"\", line 1\n" " 1.__class__\n" " ^\n" "SyntaxError: invalid decimal literal" msgstr "" ">>> 1.__class__\n" " File \"\", line 1\n" " 1.__class__\n" " ^\n" "SyntaxError: invalid decimal literal" #: ../../faq/programming.rst:859 #, fuzzy msgid "" "The solution is to separate the literal from the period with either a space " "or parentheses." msgstr "解決方案是用空格或圓括號將文字與句點分開。" #: ../../faq/programming.rst:869 msgid "How do I convert a string to a number?" msgstr "如何將字串轉換為數字?" #: ../../faq/programming.rst:871 #, fuzzy msgid "" "For integers, use the built-in :func:`int` type constructor, e.g. " "``int('144') == 144``. Similarly, :func:`float` converts to a floating-" "point number, e.g. ``float('144') == 144.0``." msgstr "" "對於整數,使用內建的 int 型別構造函式,例如``int('144') == 144``。同樣,:" "func:`float` 轉換為浮點數,例如``浮動('144')== 144.0``。" #: ../../faq/programming.rst:875 #, fuzzy msgid "" "By default, these interpret the number as decimal, so that ``int('0144') == " "144`` holds true, and ``int('0x144')`` raises :exc:`ValueError`. " "``int(string, base)`` takes the base to convert from as a second optional " "argument, so ``int( '0x144', 16) == 324``. If the base is specified as 0, " "the number is interpreted using Python's rules: a leading '0o' indicates " "octal, and '0x' indicates a hex number." msgstr "" "預設情況下,這些將數字解釋為十進位,因此 ``int('0144') == 144`` 成立,而 " "``int('0x144')`` 引發 :exc:`ValueError`。 ``int(string, base)`` 將要轉換的基" "數作為第二個可選引數,因此 ``int( '0x144', 16) == 324``。如果基數指定為 0,則" "使用 Python 的規則解釋該數字:前導 \"0o\" 表示八進位, \"0x\" 表示十六進位" "數。" #: ../../faq/programming.rst:882 #, fuzzy msgid "" "Do not use the built-in function :func:`eval` if all you need is to convert " "strings to numbers. :func:`eval` will be significantly slower and it " "presents a security risk: someone could pass you a Python expression that " "might have unwanted side effects. For example, someone could pass " "``__import__('os').system(\"rm -rf $HOME\")`` which would erase your home " "directory." msgstr "" "如果你只需要將字串轉換為數字,請不要使用內建函式 :func:`eval`。 :func:`eval` " "會顯著變慢,並且會帶來安全風險:有人可能會向你傳遞一個可能會產生不良副作用的 " "Python 運算式。例如,有人可以透過 ``__import__('os').system(\"rm -rf " "$HOME\")`` 來清除你的主目錄。" #: ../../faq/programming.rst:889 #, fuzzy msgid "" ":func:`eval` also has the effect of interpreting numbers as Python " "expressions, so that e.g. ``eval('09')`` gives a syntax error because Python " "does not allow leading '0' in a decimal number (except '0')." msgstr "" ":func:`eval` 還具有將數字解釋為 Python 運算式的效果,例如``eval('09')`` 會給" "出語法錯誤,因為 Python 不允許在十進位數中前導 '0'('0' 除外)。" #: ../../faq/programming.rst:895 msgid "How do I convert a number to a string?" msgstr "如何將數字轉換為字串?" #: ../../faq/programming.rst:897 #, fuzzy msgid "" "To convert, e.g., the number ``144`` to the string ``'144'``, use the built-" "in type constructor :func:`str`. If you want a hexadecimal or octal " "representation, use the built-in functions :func:`hex` or :func:`oct`. For " "fancy formatting, see the :ref:`f-strings` and :ref:`formatstrings` " "sections, e.g. ``\"{:04d}\".format(144)`` yields ``'0144'`` and ``\"{:.3f}\"." "format(1.0/3.0)`` yields ``'0.333'``." msgstr "" "例如,要將數字 ``144`` 轉換為字串 ``'144'``,請使用內建型別構造函式 :func:" "`str`。如果你想要十六進製或八進製表示,請使用內建函式 :func:`hex` 或 :func:" "`oct`。對於精美的格式,請參閱:ref:`f-strings` 和:ref:`formatstrings` 部分,例" "如``\"{:04d}\".format(144)`` 產生 ``'0144'`` 和 ``\"{:.3f}\"." "format(1.0/3.0)`` 產生 ``'0.333'`` ." #: ../../faq/programming.rst:906 #, fuzzy msgid "How do I modify a string in place?" msgstr "如何原地修改字串?" #: ../../faq/programming.rst:908 #, fuzzy msgid "" "You can't, because strings are immutable. In most situations, you should " "simply construct a new string from the various parts you want to assemble it " "from. However, if you need an object with the ability to modify in-place " "unicode data, try using an :class:`io.StringIO` object or the :mod:`array` " "module::" msgstr "" "你不能,因為字串是不可變的。在大多數情況下,你應該簡單地從要組裝的各個部分構" "造一個新字串。但是,如果你需要一個能夠修改原地 unicode 資料的物件,請嘗試使" "用 :class:`io.StringIO` 物件或 :mod:`array` 模組: ::" #: ../../faq/programming.rst:914 msgid "" ">>> import io\n" ">>> s = \"Hello, world\"\n" ">>> sio = io.StringIO(s)\n" ">>> sio.getvalue()\n" "'Hello, world'\n" ">>> sio.seek(7)\n" "7\n" ">>> sio.write(\"there!\")\n" "6\n" ">>> sio.getvalue()\n" "'Hello, there!'\n" "\n" ">>> import array\n" ">>> a = array.array('u', s)\n" ">>> print(a)\n" "array('u', 'Hello, world')\n" ">>> a[0] = 'y'\n" ">>> print(a)\n" "array('u', 'yello, world')\n" ">>> a.tounicode()\n" "'yello, world'" msgstr "" ">>> import io\n" ">>> s = \"Hello, world\"\n" ">>> sio = io.StringIO(s)\n" ">>> sio.getvalue()\n" "'Hello, world'\n" ">>> sio.seek(7)\n" "7\n" ">>> sio.write(\"there!\")\n" "6\n" ">>> sio.getvalue()\n" "'Hello, there!'\n" "\n" ">>> import array\n" ">>> a = array.array('u', s)\n" ">>> print(a)\n" "array('u', 'Hello, world')\n" ">>> a[0] = 'y'\n" ">>> print(a)\n" "array('u', 'yello, world')\n" ">>> a.tounicode()\n" "'yello, world'" #: ../../faq/programming.rst:938 #, fuzzy msgid "How do I use strings to call functions/methods?" msgstr "如何使用字串呼叫函式/方法?" #: ../../faq/programming.rst:940 #, fuzzy msgid "There are various techniques." msgstr "有各種各樣的技術。" #: ../../faq/programming.rst:942 #, fuzzy msgid "" "The best is to use a dictionary that maps strings to functions. The primary " "advantage of this technique is that the strings do not need to match the " "names of the functions. This is also the primary technique used to emulate " "a case construct::" msgstr "" "最好的方法是使用將字串映射到函式的字典。這種技術的主要優點是字串不需要與函式" "名稱相匹配。這也是用於模擬案例構造的主要技術: ::" #: ../../faq/programming.rst:947 msgid "" "def a():\n" " pass\n" "\n" "def b():\n" " pass\n" "\n" "dispatch = {'go': a, 'stop': b} # Note lack of parens for funcs\n" "\n" "dispatch[get_input()]() # Note trailing parens to call function" msgstr "" #: ../../faq/programming.rst:957 msgid "Use the built-in function :func:`getattr`::" msgstr "使用內建函式 :func:`getattr`: ::" #: ../../faq/programming.rst:959 msgid "" "import foo\n" "getattr(foo, 'bar')()" msgstr "" "import foo\n" "getattr(foo, 'bar')()" #: ../../faq/programming.rst:962 #, fuzzy msgid "" "Note that :func:`getattr` works on any object, including classes, class " "instances, modules, and so on." msgstr "請注意 :func:`getattr` 適用於任何物件,包括類別、類別實例、模組等。" #: ../../faq/programming.rst:965 #, fuzzy msgid "This is used in several places in the standard library, like this::" msgstr "這在標準函式庫中的幾個地方使用,如下所示: ::" #: ../../faq/programming.rst:967 msgid "" "class Foo:\n" " def do_foo(self):\n" " ...\n" "\n" " def do_bar(self):\n" " ...\n" "\n" "f = getattr(foo_instance, 'do_' + opname)\n" "f()" msgstr "" "class Foo:\n" " def do_foo(self):\n" " ...\n" "\n" " def do_bar(self):\n" " ...\n" "\n" "f = getattr(foo_instance, 'do_' + opname)\n" "f()" #: ../../faq/programming.rst:978 msgid "Use :func:`locals` to resolve the function name::" msgstr "使用 :func:`locals` 解析函式名稱: ::" #: ../../faq/programming.rst:980 msgid "" "def myFunc():\n" " print(\"hello\")\n" "\n" "fname = \"myFunc\"\n" "\n" "f = locals()[fname]\n" "f()" msgstr "" "def myFunc():\n" " print(\"hello\")\n" "\n" "fname = \"myFunc\"\n" "\n" "f = locals()[fname]\n" "f()" #: ../../faq/programming.rst:990 #, fuzzy msgid "" "Is there an equivalent to Perl's chomp() for removing trailing newlines from " "strings?" msgstr "是否有與 Perl 的 chomp() 等效的方法用於從字串中刪除尾隨換行符?" #: ../../faq/programming.rst:992 msgid "" "You can use ``S.rstrip(\"\\r\\n\")`` to remove all occurrences of any line " "terminator from the end of the string ``S`` without removing other trailing " "whitespace. If the string ``S`` represents more than one line, with several " "empty lines at the end, the line terminators for all the blank lines will be " "removed::" msgstr "" #: ../../faq/programming.rst:998 msgid "" ">>> lines = (\"line 1 \\r\\n\"\n" "... \"\\r\\n\"\n" "... \"\\r\\n\")\n" ">>> lines.rstrip(\"\\n\\r\")\n" "'line 1 '" msgstr "" ">>> lines = (\"line 1 \\r\\n\"\n" "... \"\\r\\n\"\n" "... \"\\r\\n\")\n" ">>> lines.rstrip(\"\\n\\r\")\n" "'line 1 '" #: ../../faq/programming.rst:1004 #, fuzzy msgid "" "Since this is typically only desired when reading text one line at a time, " "using ``S.rstrip()`` this way works well." msgstr "" "由於這通常只在一次讀取一行文本時才需要,因此使用 ``S.rstrip()`` 這種方式效果" "很好。" #: ../../faq/programming.rst:1009 #, fuzzy msgid "Is there a scanf() or sscanf() equivalent?" msgstr "是否有 scanf() 或 sscanf() 等價物?" #: ../../faq/programming.rst:1011 #, fuzzy msgid "Not as such." msgstr "不是這樣的。" #: ../../faq/programming.rst:1013 #, fuzzy msgid "" "For simple input parsing, the easiest approach is usually to split the line " "into whitespace-delimited words using the :meth:`~str.split` method of " "string objects and then convert decimal strings to numeric values using :" "func:`int` or :func:`float`. :meth:`!split` supports an optional \"sep\" " "parameter which is useful if the line uses something other than whitespace " "as a separator." msgstr "" "對於簡單的輸入解析,最簡單的方法通常是使用字串物件的 :meth:`~str.split` 方法" "將行拆分為以空格分隔的單詞,然後使用 :func:`int` 或將十進製字串轉換為數值:" "func:`浮動`。 :meth:`!split` 支援可選的 \"sep\" 參數,如果該行使用空格以外的" "其他內容作為分隔符,該參數很有用。" #: ../../faq/programming.rst:1019 #, fuzzy msgid "" "For more complicated input parsing, regular expressions are more powerful " "than C's ``sscanf`` and better suited for the task." msgstr "" "對於更複雜的輸入解析,正則運算式比 C 的 ``sscanf`` 更強大,更適合這項任務。" #: ../../faq/programming.rst:1024 msgid "What does 'UnicodeDecodeError' or 'UnicodeEncodeError' error mean?" msgstr "'UnicodeDecodeError' 或 'UnicodeEncodeErro' 錯誤是什麼意思?" #: ../../faq/programming.rst:1026 msgid "See the :ref:`unicode-howto`." msgstr "請參閱 :ref:`unicode-howto`。" #: ../../faq/programming.rst:1032 #, fuzzy msgid "Can I end a raw string with an odd number of backslashes?" msgstr "我可以用奇數個反斜杠結束原始字串嗎?" #: ../../faq/programming.rst:1034 #, fuzzy msgid "" "A raw string ending with an odd number of backslashes will escape the " "string's quote::" msgstr "以奇數個反斜杠結尾的原始字串將轉義字串的引號: ::" #: ../../faq/programming.rst:1036 msgid "" ">>> r'C:\\this\\will\\not\\work\\'\n" " File \"\", line 1\n" " r'C:\\this\\will\\not\\work\\'\n" " ^\n" "SyntaxError: unterminated string literal (detected at line 1)" msgstr "" ">>> r'C:\\this\\will\\not\\work\\'\n" " File \"\", line 1\n" " r'C:\\this\\will\\not\\work\\'\n" " ^\n" "SyntaxError: unterminated string literal (detected at line 1)" #: ../../faq/programming.rst:1042 #, fuzzy msgid "" "There are several workarounds for this. One is to use regular strings and " "double the backslashes::" msgstr "有幾種解決方法。一種是使用常規字串並加倍反斜杠: ::" #: ../../faq/programming.rst:1045 msgid "" ">>> 'C:\\\\this\\\\will\\\\work\\\\'\n" "'C:\\\\this\\\\will\\\\work\\\\'" msgstr "" ">>> 'C:\\\\this\\\\will\\\\work\\\\'\n" "'C:\\\\this\\\\will\\\\work\\\\'" #: ../../faq/programming.rst:1048 #, fuzzy msgid "" "Another is to concatenate a regular string containing an escaped backslash " "to the raw string::" msgstr "另一種方法是將包含轉義反斜杠的常規字串連接到原始字串: ::" #: ../../faq/programming.rst:1051 msgid "" ">>> r'C:\\this\\will\\work' '\\\\'\n" "'C:\\\\this\\\\will\\\\work\\\\'" msgstr "" ">>> r'C:\\this\\will\\work' '\\\\'\n" "'C:\\\\this\\\\will\\\\work\\\\'" #: ../../faq/programming.rst:1054 #, fuzzy msgid "" "It is also possible to use :func:`os.path.join` to append a backslash on " "Windows::" msgstr "也可以使用 :func:`os.path.join` 在 Windows 上附加反斜杠: ::" #: ../../faq/programming.rst:1056 msgid "" ">>> os.path.join(r'C:\\this\\will\\work', '')\n" "'C:\\\\this\\\\will\\\\work\\\\'" msgstr "" ">>> os.path.join(r'C:\\this\\will\\work', '')\n" "'C:\\\\this\\\\will\\\\work\\\\'" #: ../../faq/programming.rst:1059 #, fuzzy msgid "" "Note that while a backslash will \"escape\" a quote for the purposes of " "determining where the raw string ends, no escaping occurs when interpreting " "the value of the raw string. That is, the backslash remains present in the " "value of the raw string::" msgstr "" "請注意,雖然為了確定原始字串的結束位置而使用反斜杠「跳脫」引號,但在解釋原始" "字串的值時不會發生轉義。也就是說,反斜杠仍然存在於原始字串的值中: ::" #: ../../faq/programming.rst:1064 msgid "" ">>> r'backslash\\'preserved'\n" "\"backslash\\\\'preserved\"" msgstr "" ">>> r'backslash\\'preserved'\n" "\"backslash\\\\'preserved\"" #: ../../faq/programming.rst:1067 #, fuzzy msgid "Also see the specification in the :ref:`language reference `." msgstr "另請參閱 :ref:`語言參考 ` 中的規範。" #: ../../faq/programming.rst:1070 msgid "Performance" msgstr "" #: ../../faq/programming.rst:1073 msgid "My program is too slow. How do I speed it up?" msgstr "我的程式太慢了。我該如何加快速度?" #: ../../faq/programming.rst:1075 #, fuzzy msgid "" "That's a tough one, in general. First, here are a list of things to " "remember before diving further:" msgstr "" "總的來說,這是一個艱難的過程。首先,這裡列出了在進一步潛水之前要記住的事項:" #: ../../faq/programming.rst:1078 #, fuzzy msgid "" "Performance characteristics vary across Python implementations. This FAQ " "focuses on :term:`CPython`." msgstr "性能特徵因 Python 實作而異。此 FAQ 重點關注 :term:`CPython`。" #: ../../faq/programming.rst:1080 #, fuzzy msgid "" "Behaviour can vary across operating systems, especially when talking about I/" "O or multi-threading." msgstr "行為可能因作業系統而異,尤其是在談論 I/O 或多執行緒時。" #: ../../faq/programming.rst:1082 #, fuzzy msgid "" "You should always find the hot spots in your program *before* attempting to " "optimize any code (see the :mod:`profile` module)." msgstr "" "在嘗試最佳化任何程式碼\\ *之前*,你應該始終找到程式中的熱點(請參閱 :mod:" "`profile` 模組)。" #: ../../faq/programming.rst:1084 #, fuzzy msgid "" "Writing benchmark scripts will allow you to iterate quickly when searching " "for improvements (see the :mod:`timeit` module)." msgstr "" "編寫基準測試腳本將允許你在搜索改進時快速疊代(請參閱 :mod:`timeit` 模組)。" #: ../../faq/programming.rst:1086 #, fuzzy msgid "" "It is highly recommended to have good code coverage (through unit testing or " "any other technique) before potentially introducing regressions hidden in " "sophisticated optimizations." msgstr "" "強烈建議在可能引入隱藏在復雜最佳化中的回歸之前擁有良好的程式碼覆蓋率(透過單" "元測試或任何其他技術)。" #: ../../faq/programming.rst:1090 #, fuzzy msgid "" "That being said, there are many tricks to speed up Python code. Here are " "some general principles which go a long way towards reaching acceptable " "performance levels:" msgstr "" "也就是說,有很多技巧可以加速 Python 程式碼。以下是一些對達到可接受的性能水平" "大有幫助的一般原則:" #: ../../faq/programming.rst:1094 #, fuzzy msgid "" "Making your algorithms faster (or changing to faster ones) can yield much " "larger benefits than trying to sprinkle micro-optimization tricks all over " "your code." msgstr "" "讓你的演算法更快(或更改為更快的演算法)可以產生比嘗試在你的程式碼中散佈微最" "佳化技巧大得多的好處。" #: ../../faq/programming.rst:1098 #, fuzzy msgid "" "Use the right data structures. Study documentation for the :ref:`bltin-" "types` and the :mod:`collections` module." msgstr "" "使用正確的資料結構。研究 :ref:`bltin-types` 和 :mod:`collections` 模組的文" "件。" #: ../../faq/programming.rst:1101 #, fuzzy msgid "" "When the standard library provides a primitive for doing something, it is " "likely (although not guaranteed) to be faster than any alternative you may " "come up with. This is doubly true for primitives written in C, such as " "builtins and some extension types. For example, be sure to use either the :" "meth:`list.sort` built-in method or the related :func:`sorted` function to " "do sorting (and see the :ref:`sortinghowto` for examples of moderately " "advanced usage)." msgstr "" "當標準函式庫提供用於執行某些操作的原語時,它很可能(儘管不能保證)比你可能想" "出的任何替代方法都更快。對於用 C 編寫的原語,例如內建函式和一些擴充型別,情況" "更是如此。例如,請務必使用 :meth:`list.sort` 內建方法或相關的 :func:`sorted` " "函式進行排序(有關高階用法的示例,請參閱 :ref:`sortinghowto` )." #: ../../faq/programming.rst:1109 #, fuzzy msgid "" "Abstractions tend to create indirections and force the interpreter to work " "more. If the levels of indirection outweigh the amount of useful work done, " "your program will be slower. You should avoid excessive abstraction, " "especially under the form of tiny functions or methods (which are also often " "detrimental to readability)." msgstr "" "抽象往往會產生間接性並迫使直譯器工作更多。如果間接級別超過了完成的有用工作" "量,你的程式就會變慢。你應該避免過度抽象,尤其是在微小的函式或方法的形式下" "(這通常也不利於可讀性)。" #: ../../faq/programming.rst:1115 #, fuzzy msgid "" "If you have reached the limit of what pure Python can allow, there are tools " "to take you further away. For example, `Cython `_ can " "compile a slightly modified version of Python code into a C extension, and " "can be used on many different platforms. Cython can take advantage of " "compilation (and optional type annotations) to make your code significantly " "faster than when interpreted. If you are confident in your C programming " "skills, you can also :ref:`write a C extension module ` " "yourself." msgstr "" "如果你已經達到純 Python 所能允許的極限,可以使用一些工具讓你走得更遠。例如," "`Cython `_ 可以將稍微修改過的 Python 程式碼編譯成 C 擴" "充,並且可以在許多不同的平台上使用。 Cython 可以利用編譯(和可選的型別註釋)" "使你的程式碼比解釋時快得多。如果你對自己的 C 編程技能有信心,你也可以 :ref:`" "自己編寫一個 C 擴充模組 `。" #: ../../faq/programming.rst:1125 msgid "" "The wiki page devoted to `performance tips `_." msgstr "" "有個 wiki 頁面專門介紹\\ `效能改進小提示 `_。" #: ../../faq/programming.rst:1131 #, fuzzy msgid "What is the most efficient way to concatenate many strings together?" msgstr "將多個字串連接在一起的最有效方法是什麼?" #: ../../faq/programming.rst:1133 #, fuzzy msgid "" ":class:`str` and :class:`bytes` objects are immutable, therefore " "concatenating many strings together is inefficient as each concatenation " "creates a new object. In the general case, the total runtime cost is " "quadratic in the total string length." msgstr "" ":class:`str` 和 :class:`bytes` 物件是不可變的,因此將多個字串連接在一起效率低" "下,因為每次連接都會建立一個新物件。在一般情況下,總執行環境 (runtime) 成本是" "總字串長度的二次方。" #: ../../faq/programming.rst:1138 #, fuzzy msgid "" "To accumulate many :class:`str` objects, the recommended idiom is to place " "them into a list and call :meth:`str.join` at the end::" msgstr "" "要累積許多 :class:`str` 物件,推薦的習慣用法是將它們放入list中並在末尾呼叫 :" "meth:`str.join`: ::" #: ../../faq/programming.rst:1141 msgid "" "chunks = []\n" "for s in my_strings:\n" " chunks.append(s)\n" "result = ''.join(chunks)" msgstr "" #: ../../faq/programming.rst:1146 #, fuzzy msgid "(another reasonably efficient idiom is to use :class:`io.StringIO`)" msgstr "(另一個相當有效的習慣用法是使用 :class:`io.StringIO`)" #: ../../faq/programming.rst:1148 #, fuzzy msgid "" "To accumulate many :class:`bytes` objects, the recommended idiom is to " "extend a :class:`bytearray` object using in-place concatenation (the ``+=`` " "operator)::" msgstr "" "要累積許多 :class:`bytes` 物件,推薦的習慣用法是使用原地連接(``+=`` 運算子)" "擴充一個 :class:`bytearray` 物件: ::" #: ../../faq/programming.rst:1151 msgid "" "result = bytearray()\n" "for b in my_bytes_objects:\n" " result += b" msgstr "" #: ../../faq/programming.rst:1157 #, fuzzy msgid "Sequences (Tuples/Lists)" msgstr "序列(元組/list)" #: ../../faq/programming.rst:1160 #, fuzzy msgid "How do I convert between tuples and lists?" msgstr "如何在元組和list之間進行轉換?" #: ../../faq/programming.rst:1162 #, fuzzy msgid "" "The type constructor ``tuple(seq)`` converts any sequence (actually, any " "iterable) into a tuple with the same items in the same order." msgstr "" "型別構造器 ``tuple(seq)`` 將任何序列(實際上是任何可疊代物件)轉換為具有相同" "順序的相同項的元組。" #: ../../faq/programming.rst:1165 #, fuzzy msgid "" "For example, ``tuple([1, 2, 3])`` yields ``(1, 2, 3)`` and ``tuple('abc')`` " "yields ``('a', 'b', 'c')``. If the argument is a tuple, it does not make a " "copy but returns the same object, so it is cheap to call :func:`tuple` when " "you aren't sure that an object is already a tuple." msgstr "" "例如,``tuple([1, 2, 3])`` 產生 ``(1, 2, 3)`` 而 ``tuple('abc')`` 產生 " "``('a', 'b ', 'c')``。如果引數是一個元組,它不會復製而是回傳同一個物件,所以" "當你不確定一個物件是否已經是一個元組時呼叫 :func:`tuple` 是便宜的。" #: ../../faq/programming.rst:1170 #, fuzzy msgid "" "The type constructor ``list(seq)`` converts any sequence or iterable into a " "list with the same items in the same order. For example, ``list((1, 2, " "3))`` yields ``[1, 2, 3]`` and ``list('abc')`` yields ``['a', 'b', 'c']``. " "If the argument is a list, it makes a copy just like ``seq[:]`` would." msgstr "" "型別構造函式 ``list(seq)`` 將任何序列或可疊代物件轉換為具有相同順序的相同項目" "的list。例如,``list((1, 2, 3))`` 產生``[1, 2, 3]`` 和``list('abc')`` 產生" "``['a', 'b ', 'c']``。如果引數是一個list,它會像 ``seq[:]`` 那樣製作一個副" "本。" #: ../../faq/programming.rst:1177 #, fuzzy msgid "What's a negative index?" msgstr "什麼是負指數?" #: ../../faq/programming.rst:1179 #, fuzzy msgid "" "Python sequences are indexed with positive numbers and negative numbers. " "For positive numbers 0 is the first index 1 is the second index and so " "forth. For negative indices -1 is the last index and -2 is the penultimate " "(next to last) index and so forth. Think of ``seq[-n]`` as the same as " "``seq[len(seq)-n]``." msgstr "" "Python 序列使用正數和負數進行索引。對於正數,0 是第一個索引,1 是第二個索引," "依此類推。對於負索引,-1 是最後一個索引,-2 是倒數第二個(倒數第二個)索引," "依此類推。將 ``seq[-n]`` 視為與 ``seq[len(seq)-n]`` 相同。" #: ../../faq/programming.rst:1184 #, fuzzy msgid "" "Using negative indices can be very convenient. For example ``S[:-1]`` is " "all of the string except for its last character, which is useful for " "removing the trailing newline from a string." msgstr "" "使用負索引會非常方便。例如 ``S[:-1]`` 是除最後一個字元之外的所有字串,這對於" "從字串中刪除尾隨換行符很有用。" #: ../../faq/programming.rst:1190 #, fuzzy msgid "How do I iterate over a sequence in reverse order?" msgstr "如何以相反的順序疊代序列?" #: ../../faq/programming.rst:1192 #, fuzzy msgid "Use the :func:`reversed` built-in function::" msgstr "使用 :func:`reversed` 內建函式: ::" #: ../../faq/programming.rst:1194 msgid "" "for x in reversed(sequence):\n" " ... # do something with x ..." msgstr "" #: ../../faq/programming.rst:1197 #, fuzzy msgid "" "This won't touch your original sequence, but build a new copy with reversed " "order to iterate over." msgstr "這不會觸及你的原始序列,但會構建一個具有相反順序的新副本以進行疊代。" #: ../../faq/programming.rst:1202 #, fuzzy msgid "How do you remove duplicates from a list?" msgstr "如何從list中刪除重複項?" #: ../../faq/programming.rst:1204 #, fuzzy msgid "See the Python Cookbook for a long discussion of many ways to do this:" msgstr "請參閱 Python Cookbook 以獲取有關執行此操作的多種方法的詳細討論:" #: ../../faq/programming.rst:1206 msgid "https://code.activestate.com/recipes/52560/" msgstr "https://code.activestate.com/recipes/52560/" #: ../../faq/programming.rst:1208 #, fuzzy msgid "" "If you don't mind reordering the list, sort it and then scan from the end of " "the list, deleting duplicates as you go::" msgstr "" "如果你不介意重新排序list,請對其進行排序,然後從list末尾開始掃描,同時刪除重" "複項: ::" #: ../../faq/programming.rst:1211 msgid "" "if mylist:\n" " mylist.sort()\n" " last = mylist[-1]\n" " for i in range(len(mylist)-2, -1, -1):\n" " if last == mylist[i]:\n" " del mylist[i]\n" " else:\n" " last = mylist[i]" msgstr "" #: ../../faq/programming.rst:1220 #, fuzzy msgid "" "If all elements of the list may be used as set keys (i.e. they are all :term:" "`hashable`) this is often faster ::" msgstr "" "如果list的所有元素都可以用作集合鍵(即它們都是 :term:`hashable`),這通常會更" "快: ::" #: ../../faq/programming.rst:1223 msgid "mylist = list(set(mylist))" msgstr "" #: ../../faq/programming.rst:1225 #, fuzzy msgid "" "This converts the list into a set, thereby removing duplicates, and then " "back into a list." msgstr "這會將list轉換為一個集合,從而刪除重複項,然後再轉換回list。" #: ../../faq/programming.rst:1230 #, fuzzy msgid "How do you remove multiple items from a list" msgstr "如何從list中刪除多個項目" #: ../../faq/programming.rst:1232 #, fuzzy msgid "" "As with removing duplicates, explicitly iterating in reverse with a delete " "condition is one possibility. However, it is easier and faster to use slice " "replacement with an implicit or explicit forward iteration. Here are three " "variations.::" msgstr "" "與刪除重複項一樣,使用刪除條件顯式反向疊代是一種可能性。但是,透過隱式或顯式" "前向疊代使用切片替換更容易和更快。這是三種變體: ::" #: ../../faq/programming.rst:1237 msgid "" "mylist[:] = filter(keep_function, mylist)\n" "mylist[:] = (x for x in mylist if keep_condition)\n" "mylist[:] = [x for x in mylist if keep_condition]" msgstr "" #: ../../faq/programming.rst:1241 #, fuzzy msgid "The list comprehension may be fastest." msgstr "list理解可能是最快的。" #: ../../faq/programming.rst:1245 #, fuzzy msgid "How do you make an array in Python?" msgstr "你如何在 Python 中建立數組?" #: ../../faq/programming.rst:1247 #, fuzzy msgid "Use a list::" msgstr "使用 list: ::" #: ../../faq/programming.rst:1249 msgid "[\"this\", 1, \"is\", \"an\", \"array\"]" msgstr "" #: ../../faq/programming.rst:1251 #, fuzzy msgid "" "Lists are equivalent to C or Pascal arrays in their time complexity; the " "primary difference is that a Python list can contain objects of many " "different types." msgstr "" "list在時間複雜度上等同於 C 或 Pascal 數組;主要區別在於 Python list可以包含許" "多不同型別的物件。" #: ../../faq/programming.rst:1254 #, fuzzy msgid "" "The ``array`` module also provides methods for creating arrays of fixed " "types with compact representations, but they are slower to index than " "lists. Also note that `NumPy `_ and other third party " "packages define array-like structures with various characteristics as well." msgstr "" "``array`` 模組還提供了建立具有緊湊表示的固定型別數組的方法,但它們的索引速度" "比list慢。另請注意,`NumPy `_ 和其他第三方包也定義了具有" "各種特徵的類似數組的結構。" #: ../../faq/programming.rst:1260 #, fuzzy msgid "" "To get Lisp-style linked lists, you can emulate *cons cells* using tuples::" msgstr "要獲得 Lisp 風格的鍊錶,你可以使用元組模擬 *cons cells*: ::" #: ../../faq/programming.rst:1262 msgid "lisp_list = (\"like\", (\"this\", (\"example\", None) ) )" msgstr "" #: ../../faq/programming.rst:1264 #, fuzzy msgid "" "If mutability is desired, you could use lists instead of tuples. Here the " "analogue of a Lisp *car* is ``lisp_list[0]`` and the analogue of *cdr* is " "``lisp_list[1]``. Only do this if you're sure you really need to, because " "it's usually a lot slower than using Python lists." msgstr "" "如果需要可變性,你可以使用list而不是元組。這裡 Lisp *car* 的類比是 " "``lisp_list[0]`` 而 *cdr* 的類比是 ``lisp_list[1]``。只有在確定確實需要時才這" "樣做,因為它通常比使用 Python list慢很多。" #: ../../faq/programming.rst:1273 #, fuzzy msgid "How do I create a multidimensional list?" msgstr "如何建立多維 list?" #: ../../faq/programming.rst:1275 #, fuzzy msgid "You probably tried to make a multidimensional array like this::" msgstr "你可能嘗試製作這樣的多維數組: ::" #: ../../faq/programming.rst:1277 msgid ">>> A = [[None] * 2] * 3" msgstr ">>> A = [[None] * 2] * 3" #: ../../faq/programming.rst:1279 msgid "This looks correct if you print it:" msgstr "如果你印出它,這看起來是正確的:" #: ../../faq/programming.rst:1285 msgid "" ">>> A\n" "[[None, None], [None, None], [None, None]]" msgstr "" ">>> A\n" "[[None, None], [None, None], [None, None]]" #: ../../faq/programming.rst:1290 #, fuzzy msgid "But when you assign a value, it shows up in multiple places:" msgstr "但是當你分配一個值時,它會出現在多個地方:" #: ../../faq/programming.rst:1296 msgid "" ">>> A[0][0] = 5\n" ">>> A\n" "[[5, None], [5, None], [5, None]]" msgstr "" #: ../../faq/programming.rst:1302 #, fuzzy msgid "" "The reason is that replicating a list with ``*`` doesn't create copies, it " "only creates references to the existing objects. The ``*3`` creates a list " "containing 3 references to the same list of length two. Changes to one row " "will show in all rows, which is almost certainly not what you want." msgstr "" "原因是複製帶有 ``*`` 的list不會建立副本,它只會建立對現有物件的參照。 ``*3`` " "建立一個list,其中包含 3 個對長度為 2 的相同list的參照。對一行的更改將顯示在" "所有行中,這幾乎肯定不是你想要的。" #: ../../faq/programming.rst:1307 #, fuzzy msgid "" "The suggested approach is to create a list of the desired length first and " "then fill in each element with a newly created list::" msgstr "建議的方法是先建立所需長度的list,然後用新建立的list填充每個元素: ::" #: ../../faq/programming.rst:1310 msgid "" "A = [None] * 3\n" "for i in range(3):\n" " A[i] = [None] * 2" msgstr "" #: ../../faq/programming.rst:1314 #, fuzzy msgid "" "This generates a list containing 3 different lists of length two. You can " "also use a list comprehension::" msgstr "" "這會生成一個包含 3 個長度為 2 的不同list的list。你還可以使用list推導: ::" #: ../../faq/programming.rst:1317 msgid "" "w, h = 2, 3\n" "A = [[None] * w for i in range(h)]" msgstr "" #: ../../faq/programming.rst:1320 #, fuzzy msgid "" "Or, you can use an extension that provides a matrix datatype; `NumPy " "`_ is the best known." msgstr "" "或者,你可以使用提供矩陣資料型別的擴充; `NumPy `_ 是最著" "名的。" #: ../../faq/programming.rst:1325 #, fuzzy msgid "How do I apply a method or function to a sequence of objects?" msgstr "如何將方法或函式應用於一系列物件?" #: ../../faq/programming.rst:1327 #, fuzzy msgid "" "To call a method or function and accumulate the return values is a list, a :" "term:`list comprehension` is an elegant solution::" msgstr "" "呼叫一個方法或函式並累積回傳值是一個list,一個 :term:`list comprehension` 是" "一個優雅的解決方案: ::" #: ../../faq/programming.rst:1330 msgid "" "result = [obj.method() for obj in mylist]\n" "\n" "result = [function(obj) for obj in mylist]" msgstr "" #: ../../faq/programming.rst:1334 #, fuzzy msgid "" "To just run the method or function without saving the return values, a " "plain :keyword:`for` loop will suffice::" msgstr "要只運行方法或函式而不保存回傳值,一個普通的 for 循環就足夠了: ::" #: ../../faq/programming.rst:1337 msgid "" "for obj in mylist:\n" " obj.method()\n" "\n" "for obj in mylist:\n" " function(obj)" msgstr "" #: ../../faq/programming.rst:1346 #, fuzzy msgid "" "Why does a_tuple[i] += ['item'] raise an exception when the addition works?" msgstr "為什麼 a_tuple[i] += ['item'] 在加法工作時引發例外?" #: ../../faq/programming.rst:1348 #, fuzzy msgid "" "This is because of a combination of the fact that augmented assignment " "operators are *assignment* operators, and the difference between mutable and " "immutable objects in Python." msgstr "" "這是因為增強賦值運算子是 *assignment* 運算子這一事實,以及 Python 中可變物件" "和不可變物件之間的區別。" #: ../../faq/programming.rst:1352 #, fuzzy msgid "" "This discussion applies in general when augmented assignment operators are " "applied to elements of a tuple that point to mutable objects, but we'll use " "a ``list`` and ``+=`` as our exemplar." msgstr "" "當擴充賦值運算子應用於指向可變物件的元組元素時,此討論通常適用,但我們將使用 " "``list`` 和 ``+=\" 作為示例。" #: ../../faq/programming.rst:1356 #, fuzzy msgid "If you wrote::" msgstr "如果你寫了: ::" #: ../../faq/programming.rst:1358 msgid "" ">>> a_tuple = (1, 2)\n" ">>> a_tuple[0] += 1\n" "Traceback (most recent call last):\n" " ...\n" "TypeError: 'tuple' object does not support item assignment" msgstr "" #: ../../faq/programming.rst:1364 #, fuzzy msgid "" "The reason for the exception should be immediately clear: ``1`` is added to " "the object ``a_tuple[0]`` points to (``1``), producing the result object, " "``2``, but when we attempt to assign the result of the computation, ``2``, " "to element ``0`` of the tuple, we get an error because we can't change what " "an element of a tuple points to." msgstr "" "例外的原因應該立即清楚:``1`` 被新增到物件``a_tuple[0]`` 指向 (``1``),產生結" "果物件,``2``,但是當我們嘗試將計算結果 ``2`` 分配給元組的元素 ``0`` 時,我們" "會得到一個錯誤,因為我們無法更改元組的元素指向的內容。" #: ../../faq/programming.rst:1370 #, fuzzy msgid "" "Under the covers, what this augmented assignment statement is doing is " "approximately this::" msgstr "在幕後,這個擴充賦值陳述式所做的大致是這樣的: ::" #: ../../faq/programming.rst:1373 msgid "" ">>> result = a_tuple[0] + 1\n" ">>> a_tuple[0] = result\n" "Traceback (most recent call last):\n" " ...\n" "TypeError: 'tuple' object does not support item assignment" msgstr "" #: ../../faq/programming.rst:1379 #, fuzzy msgid "" "It is the assignment part of the operation that produces the error, since a " "tuple is immutable." msgstr "產生錯誤的是操作的賦值部分,因為元組是不可變的。" #: ../../faq/programming.rst:1382 #, fuzzy msgid "When you write something like::" msgstr "當你寫這樣的東西時: ::" #: ../../faq/programming.rst:1384 msgid "" ">>> a_tuple = (['foo'], 'bar')\n" ">>> a_tuple[0] += ['item']\n" "Traceback (most recent call last):\n" " ...\n" "TypeError: 'tuple' object does not support item assignment" msgstr "" #: ../../faq/programming.rst:1390 #, fuzzy msgid "" "The exception is a bit more surprising, and even more surprising is the fact " "that even though there was an error, the append worked::" msgstr "這個例外有點令人驚訝,更令人驚訝的是即使出現錯誤,追加仍然有效: ::" #: ../../faq/programming.rst:1393 msgid "" ">>> a_tuple[0]\n" "['foo', 'item']" msgstr "" ">>> a_tuple[0]\n" "['foo', 'item']" #: ../../faq/programming.rst:1396 #, fuzzy msgid "" "To see why this happens, you need to know that (a) if an object implements " "an :meth:`~object.__iadd__` magic method, it gets called when the ``+=`` " "augmented assignment is executed, and its return value is what gets used in " "the assignment statement; and (b) for lists, :meth:`!__iadd__` is equivalent " "to calling :meth:`!extend` on the list and returning the list. That's why " "we say that for lists, ``+=`` is a \"shorthand\" for :meth:`!list.extend`::" msgstr "" "要了解為什麼會發生這種情況,你需要知道 (a) 如果一個物件實作了一個 :meth:" "`~object.__iadd__` 魔術方法,它會在執行 ``+=`` 增廣賦值時被呼叫,並且它的回傳" "value 是賦值陳述式中使用的值; (b) 對於list,:meth:`!__iadd__` 相當於在list上" "呼叫 :meth:`!extend` 並回傳list。這就是為什麼我們說對於list,``+=`` 是 :meth:" "`!list.extend` 的「簡寫」: ::" #: ../../faq/programming.rst:1404 msgid "" ">>> a_list = []\n" ">>> a_list += [1]\n" ">>> a_list\n" "[1]" msgstr "" ">>> a_list = []\n" ">>> a_list += [1]\n" ">>> a_list\n" "[1]" #: ../../faq/programming.rst:1409 msgid "This is equivalent to::" msgstr "這等價於: ::" #: ../../faq/programming.rst:1411 msgid "" ">>> result = a_list.__iadd__([1])\n" ">>> a_list = result" msgstr "" ">>> result = a_list.__iadd__([1])\n" ">>> a_list = result" #: ../../faq/programming.rst:1414 #, fuzzy msgid "" "The object pointed to by a_list has been mutated, and the pointer to the " "mutated object is assigned back to ``a_list``. The end result of the " "assignment is a no-op, since it is a pointer to the same object that " "``a_list`` was previously pointing to, but the assignment still happens." msgstr "" "a_list 指向的物件已經發生變異,指向變異物件的指標被分配回 ``a_list``。賦值的" "最終結果是空操作,因為它是一個指向與 ``a_list`` 先前指向的同一物件的指標,但" "賦值仍然發生。" #: ../../faq/programming.rst:1419 #, fuzzy msgid "Thus, in our tuple example what is happening is equivalent to::" msgstr "因此,在我們的元組示例中,發生的事情等同於: ::" #: ../../faq/programming.rst:1421 msgid "" ">>> result = a_tuple[0].__iadd__(['item'])\n" ">>> a_tuple[0] = result\n" "Traceback (most recent call last):\n" " ...\n" "TypeError: 'tuple' object does not support item assignment" msgstr "" #: ../../faq/programming.rst:1427 #, fuzzy msgid "" "The :meth:`!__iadd__` succeeds, and thus the list is extended, but even " "though ``result`` points to the same object that ``a_tuple[0]`` already " "points to, that final assignment still results in an error, because tuples " "are immutable." msgstr "" ":meth:`!__iadd__` 成功,因此list被擴充,但即使 ``result`` 指向與 " "``a_tuple[0]`` 已經指向的同一個物件,最終的賦值仍然導致一個錯誤,因為元組是不" "可變的。" #: ../../faq/programming.rst:1433 #, fuzzy msgid "" "I want to do a complicated sort: can you do a Schwartzian Transform in " "Python?" msgstr "我想做一個複雜的排序:你能用 Python 做一個 Schwartzian 變換嗎?" #: ../../faq/programming.rst:1435 #, fuzzy msgid "" "The technique, attributed to Randal Schwartz of the Perl community, sorts " "the elements of a list by a metric which maps each element to its \"sort " "value\". In Python, use the ``key`` argument for the :meth:`list.sort` " "method::" msgstr "" "該技術歸功於 Perl 社區的 Randal Schwartz,它透過將每個元素映射到其「排序值」" "的度量對list的元素進行排序。在 Python 中,對 :meth:`list.sort` 方法使用 " "``key`` 引數: ::" #: ../../faq/programming.rst:1439 msgid "" "Isorted = L[:]\n" "Isorted.sort(key=lambda s: int(s[10:15]))" msgstr "" "Isorted = L[:]\n" "Isorted.sort(key=lambda s: int(s[10:15]))" #: ../../faq/programming.rst:1444 #, fuzzy msgid "How can I sort one list by values from another list?" msgstr "如何根據另一個list中的值對一個list進行排序?" #: ../../faq/programming.rst:1446 #, fuzzy msgid "" "Merge them into an iterator of tuples, sort the resulting list, and then " "pick out the element you want. ::" msgstr "" "將它們合併到一個元組疊代器中,對結果list進行排序,然後挑選出你想要的元" "素。: ::" #: ../../faq/programming.rst:1449 msgid "" ">>> list1 = [\"what\", \"I'm\", \"sorting\", \"by\"]\n" ">>> list2 = [\"something\", \"else\", \"to\", \"sort\"]\n" ">>> pairs = zip(list1, list2)\n" ">>> pairs = sorted(pairs)\n" ">>> pairs\n" "[(\"I'm\", 'else'), ('by', 'sort'), ('sorting', 'to'), ('what', " "'something')]\n" ">>> result = [x[1] for x in pairs]\n" ">>> result\n" "['else', 'sort', 'to', 'something']" msgstr "" ">>> list1 = [\"what\", \"I'm\", \"sorting\", \"by\"]\n" ">>> list2 = [\"something\", \"else\", \"to\", \"sort\"]\n" ">>> pairs = zip(list1, list2)\n" ">>> pairs = sorted(pairs)\n" ">>> pairs\n" "[(\"I'm\", 'else'), ('by', 'sort'), ('sorting', 'to'), ('what', " "'something')]\n" ">>> result = [x[1] for x in pairs]\n" ">>> result\n" "['else', 'sort', 'to', 'something']" #: ../../faq/programming.rst:1461 msgid "Objects" msgstr "物件" #: ../../faq/programming.rst:1464 msgid "What is a class?" msgstr "什麼是類別 (class)?" #: ../../faq/programming.rst:1466 #, fuzzy msgid "" "A class is the particular object type created by executing a class " "statement. Class objects are used as templates to create instance objects, " "which embody both the data (attributes) and code (methods) specific to a " "datatype." msgstr "" "類別是透過執行類別陳述式建立的特定物件型別。類別物件用作建立實例物件的模板," "實例物件包含特定於資料型別的資料(屬性)和程式碼(方法)。" #: ../../faq/programming.rst:1470 #, fuzzy msgid "" "A class can be based on one or more other classes, called its base " "class(es). It then inherits the attributes and methods of its base classes. " "This allows an object model to be successively refined by inheritance. You " "might have a generic ``Mailbox`` class that provides basic accessor methods " "for a mailbox, and subclasses such as ``MboxMailbox``, ``MaildirMailbox``, " "``OutlookMailbox`` that handle various specific mailbox formats." msgstr "" "一個類別可以基於一個或多個其他類別,稱為它的基底類別。然後它繼承其基底類別的" "屬性和方法。這允許物件模型透過繼承不斷地細化。你可能有一個通用的 ``Mailbox`` " "類別,它為郵箱提供基本的存取器方法,以及處理各種特定郵箱格式的子類別,例如 " "``MboxMailbox`` 、 ``MaildirMailbox`` 、 ``OutlookMailbox`` 。" #: ../../faq/programming.rst:1479 msgid "What is a method?" msgstr "什麼是方法 (method)?" #: ../../faq/programming.rst:1481 #, fuzzy msgid "" "A method is a function on some object ``x`` that you normally call as ``x." "name(arguments...)``. Methods are defined as functions inside the class " "definition::" msgstr "" "方法是一些物件 ``x`` 上的函式,你通常將其稱為 ``x.name(arguments...)`` 。方法" "在類別定義中被定義為函式: ::" #: ../../faq/programming.rst:1485 msgid "" "class C:\n" " def meth(self, arg):\n" " return arg * 2 + self.attribute" msgstr "" "class C:\n" " def meth(self, arg):\n" " return arg * 2 + self.attribute" #: ../../faq/programming.rst:1491 #, fuzzy msgid "What is self?" msgstr "什麼是自我?" #: ../../faq/programming.rst:1493 #, fuzzy msgid "" "Self is merely a conventional name for the first argument of a method. A " "method defined as ``meth(self, a, b, c)`` should be called as ``x.meth(a, b, " "c)`` for some instance ``x`` of the class in which the definition occurs; " "the called method will think it is called as ``meth(x, a, b, c)``." msgstr "" "Self 只是方法第一個引數的約定名稱。一個定義為 ``meth(self, a, b, c)`` 的方法" "應該被呼叫為 ``x.meth(a, b, c)`` 對於其中類別的某個實例 ``x``定義發生;被呼叫" "的方法會認為它被稱為 ``meth(x, a, b, c)`` 。" #: ../../faq/programming.rst:1498 msgid "See also :ref:`why-self`." msgstr "另請參閱 :ref:`why-self`。" #: ../../faq/programming.rst:1502 #, fuzzy msgid "" "How do I check if an object is an instance of a given class or of a subclass " "of it?" msgstr "如何檢查一個物件是給定類別的實例還是它的子類別的實例?" #: ../../faq/programming.rst:1504 #, fuzzy msgid "" "Use the built-in function :func:`isinstance(obj, cls) `. You " "can check if an object is an instance of any of a number of classes by " "providing a tuple instead of a single class, e.g. ``isinstance(obj, (class1, " "class2, ...))``, and can also check whether an object is one of Python's " "built-in types, e.g. ``isinstance(obj, str)`` or ``isinstance(obj, (int, " "float, complex))``." msgstr "" "使用內建函式 :func:`isinstance(obj, cls) `。你可以透過提供元組而" "不是單個類別來檢查物件是否是多個類別中的任何一個的實例,例如" "``isinstance(obj, (class1, class2, ...))``,還可以檢查物件是否是 Python 的內" "置型別之一,例如``isinstance(obj, str)`` 或 ``isinstance(obj, (int, float, " "complex))``。" #: ../../faq/programming.rst:1511 #, fuzzy msgid "" "Note that :func:`isinstance` also checks for virtual inheritance from an :" "term:`abstract base class`. So, the test will return ``True`` for a " "registered class even if hasn't directly or indirectly inherited from it. " "To test for \"true inheritance\", scan the :term:`MRO` of the class:" msgstr "" "請注意:func:`isinstance` 還檢查來自:term:`抽象基底類別` 的虛擬繼承。因此,測" "試將為已註冊的類別回傳 ``True``,即使沒有直接或間接繼承自它。要測試「真正的繼" "承」,請掃描該類別的 MRO:" #: ../../faq/programming.rst:1516 msgid "" "from collections.abc import Mapping\n" "\n" "class P:\n" " pass\n" "\n" "class C(P):\n" " pass\n" "\n" "Mapping.register(P)" msgstr "" "from collections.abc import Mapping\n" "\n" "class P:\n" " pass\n" "\n" "class C(P):\n" " pass\n" "\n" "Mapping.register(P)" #: ../../faq/programming.rst:1528 msgid "" ">>> c = C()\n" ">>> isinstance(c, C) # direct\n" "True\n" ">>> isinstance(c, P) # indirect\n" "True\n" ">>> isinstance(c, Mapping) # virtual\n" "True\n" "\n" "# Actual inheritance chain\n" ">>> type(c).__mro__\n" "(, , )\n" "\n" "# Test for \"true inheritance\"\n" ">>> Mapping in type(c).__mro__\n" "False" msgstr "" #: ../../faq/programming.rst:1546 #, fuzzy msgid "" "Note that most programs do not use :func:`isinstance` on user-defined " "classes very often. If you are developing the classes yourself, a more " "proper object-oriented style is to define methods on the classes that " "encapsulate a particular behaviour, instead of checking the object's class " "and doing a different thing based on what class it is. For example, if you " "have a function that does something::" msgstr "" "請注意,大多數程式不會經常在使用者定義的類別上使用 :func:`isinstance`。如果你" "自己開發類別,更合適的面向物件風格是在封裝特定行為的類別上定義方法,而不是檢" "查物件的類別並根據它是什麼類別做不同的事情。例如,如果你有一個函式做某事: ::" #: ../../faq/programming.rst:1553 msgid "" "def search(obj):\n" " if isinstance(obj, Mailbox):\n" " ... # code to search a mailbox\n" " elif isinstance(obj, Document):\n" " ... # code to search a document\n" " elif ..." msgstr "" "def search(obj):\n" " if isinstance(obj, Mailbox):\n" " ... # code to search a mailbox\n" " elif isinstance(obj, Document):\n" " ... # code to search a document\n" " elif ..." #: ../../faq/programming.rst:1560 #, fuzzy msgid "" "A better approach is to define a ``search()`` method on all the classes and " "just call it::" msgstr "更好的方法是在所有類別上定義一個 ``search()`` 方法,然後呼叫它: ::" #: ../../faq/programming.rst:1563 msgid "" "class Mailbox:\n" " def search(self):\n" " ... # code to search a mailbox\n" "\n" "class Document:\n" " def search(self):\n" " ... # code to search a document\n" "\n" "obj.search()" msgstr "" #: ../../faq/programming.rst:1575 #, fuzzy msgid "What is delegation?" msgstr "什麼是委派?" #: ../../faq/programming.rst:1577 #, fuzzy msgid "" "Delegation is an object oriented technique (also called a design pattern). " "Let's say you have an object ``x`` and want to change the behaviour of just " "one of its methods. You can create a new class that provides a new " "implementation of the method you're interested in changing and delegates all " "other methods to the corresponding method of ``x``." msgstr "" "委託是一種面向物件的技術(也稱為設計模式)。假設你有一個物件 ``x`` 並且只想更" "改其中一個方法的行為。你可以建立一個新類別,它提供你感興趣的方法的新實作,並" "將所有其他方法委託給 ``x`` 的相應方法。" #: ../../faq/programming.rst:1583 #, fuzzy msgid "" "Python programmers can easily implement delegation. For example, the " "following class implements a class that behaves like a file but converts all " "written data to uppercase::" msgstr "" "Python 程式員可以輕鬆實作委託。例如,下面的類別實作了一個行為類似於檔案但將所" "有寫入資料轉換為大寫的類別: ::" #: ../../faq/programming.rst:1587 msgid "" "class UpperOut:\n" "\n" " def __init__(self, outfile):\n" " self._outfile = outfile\n" "\n" " def write(self, s):\n" " self._outfile.write(s.upper())\n" "\n" " def __getattr__(self, name):\n" " return getattr(self._outfile, name)" msgstr "" "class UpperOut:\n" "\n" " def __init__(self, outfile):\n" " self._outfile = outfile\n" "\n" " def write(self, s):\n" " self._outfile.write(s.upper())\n" "\n" " def __getattr__(self, name):\n" " return getattr(self._outfile, name)" #: ../../faq/programming.rst:1598 #, fuzzy msgid "" "Here the ``UpperOut`` class redefines the ``write()`` method to convert the " "argument string to uppercase before calling the underlying ``self._outfile." "write()`` method. All other methods are delegated to the underlying ``self." "_outfile`` object. The delegation is accomplished via the :meth:`~object." "__getattr__` method; consult :ref:`the language reference ` for more information about controlling attribute access." msgstr "" "這裡的 ``UpperOut`` 類別重新定義了``write()`` 方法,在呼叫底層的``self." "_outfile.write()`` 方法之前將引數字串轉換為大寫。所有其他方法都委託給底層的 " "``self._outfile`` 物件。委託是透過 :meth:`~object.__getattr__` 方法完成的;有" "關控制屬性存取的更多資訊,請參閱語言參考 。" #: ../../faq/programming.rst:1605 #, fuzzy msgid "" "Note that for more general cases delegation can get trickier. When " "attributes must be set as well as retrieved, the class must define a :meth:" "`~object.__setattr__` method too, and it must do so carefully. The basic " "implementation of :meth:`!__setattr__` is roughly equivalent to the " "following::" msgstr "" "請注意,對於更一般的情況,委託可能會變得更加棘手。當必須設定和檢索屬性時,該" "類別也必須定義一個 :meth:`~object.__setattr__` 方法,而且必須小心謹慎。 :" "meth:`!__setattr__` 的基本實作大致等同於以下: ::" #: ../../faq/programming.rst:1610 msgid "" "class X:\n" " ...\n" " def __setattr__(self, name, value):\n" " self.__dict__[name] = value\n" " ..." msgstr "" "class X:\n" " ...\n" " def __setattr__(self, name, value):\n" " self.__dict__[name] = value\n" " ..." #: ../../faq/programming.rst:1616 #, fuzzy msgid "" "Most :meth:`!__setattr__` implementations must modify :meth:`self.__dict__ " "` to store local state for self without causing an infinite " "recursion." msgstr "" "大多數 :meth:`!__setattr__` 實作必須修改 :meth:`self.__dict__ ` 以存儲 self 的本地狀態,而不會導致無限遞迴。" #: ../../faq/programming.rst:1622 #, fuzzy msgid "" "How do I call a method defined in a base class from a derived class that " "extends it?" msgstr "如何從擴充它的衍生類別呼叫基底類別中定義的方法?" #: ../../faq/programming.rst:1624 msgid "Use the built-in :func:`super` function::" msgstr "使用內建的 :func:`super` 函式: ::" #: ../../faq/programming.rst:1626 msgid "" "class Derived(Base):\n" " def meth(self):\n" " super().meth() # calls Base.meth" msgstr "" "class Derived(Base):\n" " def meth(self):\n" " super().meth() # calls Base.meth" #: ../../faq/programming.rst:1630 #, fuzzy msgid "" "In the example, :func:`super` will automatically determine the instance from " "which it was called (the ``self`` value), look up the :term:`method " "resolution order` (MRO) with ``type(self).__mro__``, and return the next in " "line after ``Derived`` in the MRO: ``Base``." msgstr "" "在示例中,:func:`super` 將自動確定呼叫它的實例(``self`` 值),使用 " "``type(self ).__mro__``,並回傳 MRO 中``Derived`` 之後的下一行:``Base``。" #: ../../faq/programming.rst:1637 #, fuzzy msgid "How can I organize my code to make it easier to change the base class?" msgstr "我如何組織我的程式碼以便更容易地更改基底類別?" #: ../../faq/programming.rst:1639 #, fuzzy msgid "" "You could assign the base class to an alias and derive from the alias. Then " "all you have to change is the value assigned to the alias. Incidentally, " "this trick is also handy if you want to decide dynamically (e.g. depending " "on availability of resources) which base class to use. Example::" msgstr "" "你可以將基底類別分配給別名並從別名衍生。然後,你只需更改分配給別名的值。順便" "說一句,如果你想動態決定(例如,取決於資源的可用性)使用哪個基底類別,這個技" "巧也很方便。例子: ::" #: ../../faq/programming.rst:1644 msgid "" "class Base:\n" " ...\n" "\n" "BaseAlias = Base\n" "\n" "class Derived(BaseAlias):\n" " ..." msgstr "" "class Base:\n" " ...\n" "\n" "BaseAlias = Base\n" "\n" "class Derived(BaseAlias):\n" " ..." #: ../../faq/programming.rst:1654 #, fuzzy msgid "How do I create static class data and static class methods?" msgstr "如何建立靜態類別資料和靜態類別方法?" #: ../../faq/programming.rst:1656 #, fuzzy msgid "" "Both static data and static methods (in the sense of C++ or Java) are " "supported in Python." msgstr "Python 支援靜態資料和靜態方法(在 C++ 或 Java 的意義上)。" #: ../../faq/programming.rst:1659 #, fuzzy msgid "" "For static data, simply define a class attribute. To assign a new value to " "the attribute, you have to explicitly use the class name in the assignment::" msgstr "" "對於靜態資料,只需定義一個類別屬性即可。要為屬性分配新值,你必須在分配中顯式" "使用類別名: ::" #: ../../faq/programming.rst:1662 msgid "" "class C:\n" " count = 0 # number of times C.__init__ called\n" "\n" " def __init__(self):\n" " C.count = C.count + 1\n" "\n" " def getcount(self):\n" " return C.count # or return self.count" msgstr "" #: ../../faq/programming.rst:1671 #, fuzzy msgid "" "``c.count`` also refers to ``C.count`` for any ``c`` such that " "``isinstance(c, C)`` holds, unless overridden by ``c`` itself or by some " "class on the base-class search path from ``c.__class__`` back to ``C``." msgstr "" "``c.count`` 還指代任何 ``c`` 的 ``C.count`` 使得 ``isinstance(c, C)`` 成立," "除非被 ``c`` 本身或某些人覆蓋從 ``c.__class__`` 回到 ``C`` 的基底類別搜索路徑" "上的類別。" #: ../../faq/programming.rst:1675 #, fuzzy msgid "" "Caution: within a method of C, an assignment like ``self.count = 42`` " "creates a new and unrelated instance named \"count\" in ``self``'s own " "dict. Rebinding of a class-static data name must always specify the class " "whether inside a method or not::" msgstr "" "注意:在 C 的方法中,像 self.count = 42 這樣的賦值會在 self 自己的字典中建立" "一個名為 \"count\" 的新的不相關實例。類別靜態資料名稱的重新綁定必須始終指定類" "別是否在方法內: ::" #: ../../faq/programming.rst:1680 msgid "C.count = 314" msgstr "C.count = 314" #: ../../faq/programming.rst:1682 msgid "Static methods are possible::" msgstr "靜態方法是可能的: ::" #: ../../faq/programming.rst:1684 msgid "" "class C:\n" " @staticmethod\n" " def static(arg1, arg2, arg3):\n" " # No 'self' parameter!\n" " ..." msgstr "" "class C:\n" " @staticmethod\n" " def static(arg1, arg2, arg3):\n" " # 沒有 'self' 參數!\n" " ..." #: ../../faq/programming.rst:1690 #, fuzzy msgid "" "However, a far more straightforward way to get the effect of a static method " "is via a simple module-level function::" msgstr "" "然而,獲得靜態方法效果的一種更直接的方法是透過一個簡單的模組級函式: ::" #: ../../faq/programming.rst:1693 msgid "" "def getcount():\n" " return C.count" msgstr "" "def getcount():\n" " return C.count" #: ../../faq/programming.rst:1696 #, fuzzy msgid "" "If your code is structured so as to define one class (or tightly related " "class hierarchy) per module, this supplies the desired encapsulation." msgstr "" "如果你的程式碼結構化以便為每個模組定義一個類別(或緊密相關的類別層次結構)," "則這提供了所需的封裝。" #: ../../faq/programming.rst:1701 #, fuzzy msgid "How can I overload constructors (or methods) in Python?" msgstr "如何在 Python 中重載構造函式(或方法)?" #: ../../faq/programming.rst:1703 #, fuzzy msgid "" "This answer actually applies to all methods, but the question usually comes " "up first in the context of constructors." msgstr "" "這個答案實際上適用於所有方法,但這個問題通常首先出現在構造函式的上下文中。" #: ../../faq/programming.rst:1706 msgid "In C++ you'd write" msgstr "在 C++ 中你會寫成" #: ../../faq/programming.rst:1708 msgid "" "class C {\n" " C() { cout << \"No arguments\\n\"; }\n" " C(int i) { cout << \"Argument is \" << i << \"\\n\"; }\n" "}" msgstr "" "class C {\n" " C() { cout << \"No arguments\\n\"; }\n" " C(int i) { cout << \"Argument is \" << i << \"\\n\"; }\n" "}" #: ../../faq/programming.rst:1715 #, fuzzy msgid "" "In Python you have to write a single constructor that catches all cases " "using default arguments. For example::" msgstr "" "在 Python 中,你必須編寫一個構造函式來捕獲所有使用預設引數的情況。例如: ::" #: ../../faq/programming.rst:1718 msgid "" "class C:\n" " def __init__(self, i=None):\n" " if i is None:\n" " print(\"No arguments\")\n" " else:\n" " print(\"Argument is\", i)" msgstr "" "class C:\n" " def __init__(self, i=None):\n" " if i is None:\n" " print(\"No arguments\")\n" " else:\n" " print(\"Argument is\", i)" #: ../../faq/programming.rst:1725 #, fuzzy msgid "This is not entirely equivalent, but close enough in practice." msgstr "這並不完全等價,但在實踐中足夠接近。" #: ../../faq/programming.rst:1727 #, fuzzy msgid "You could also try a variable-length argument list, e.g. ::" msgstr "你也可以嘗試可變長度引數 list,例如: ::" #: ../../faq/programming.rst:1729 msgid "" "def __init__(self, *args):\n" " ..." msgstr "" "def __init__(self, *args):\n" " ..." #: ../../faq/programming.rst:1732 #, fuzzy msgid "The same approach works for all method definitions." msgstr "相同的方法適用於所有方法定義。" #: ../../faq/programming.rst:1736 #, fuzzy msgid "I try to use __spam and I get an error about _SomeClassName__spam." msgstr "我嘗試使用 __spam,但收到有關 _SomeClassName__spam 的錯誤。" #: ../../faq/programming.rst:1738 #, fuzzy msgid "" "Variable names with double leading underscores are \"mangled\" to provide a " "simple but effective way to define class private variables. Any identifier " "of the form ``__spam`` (at least two leading underscores, at most one " "trailing underscore) is textually replaced with ``_classname__spam``, where " "``classname`` is the current class name with any leading underscores " "stripped." msgstr "" "帶有雙前導底線的變數名被「破壞」以提供一種簡單但有效的方法來定義類別私有變" "數。 ``__spam`` 形式的任何標識器(至少兩個前導底線,最多一個尾隨底線)在文本" "上替換為 ``_classname__spam``,其中 ``classname`` 是當前類別名,所有前導底線" "被去除。" #: ../../faq/programming.rst:1744 msgid "" "The identifier can be used unchanged within the class, but to access it " "outside the class, the mangled name must be used:" msgstr "" #: ../../faq/programming.rst:1747 msgid "" "class A:\n" " def __one(self):\n" " return 1\n" " def two(self):\n" " return 2 * self.__one()\n" "\n" "class B(A):\n" " def three(self):\n" " return 3 * self._A__one()\n" "\n" "four = 4 * A()._A__one()" msgstr "" "class A:\n" " def __one(self):\n" " return 1\n" " def two(self):\n" " return 2 * self.__one()\n" "\n" "class B(A):\n" " def three(self):\n" " return 3 * self._A__one()\n" "\n" "four = 4 * A()._A__one()" #: ../../faq/programming.rst:1761 #, fuzzy msgid "" "In particular, this does not guarantee privacy since an outside user can " "still deliberately access the private attribute; many Python programmers " "never bother to use private variable names at all." msgstr "" "這並不能保證隱私:外部使用者仍然可以故意存取 \"_classname__spam\" 屬性,並且" "私有值在物件的 __dict__ 中可見。許多 Python 程式員根本懶得使用私有變數名。" #: ../../faq/programming.rst:1767 msgid "" "The :ref:`private name mangling specifications ` for " "details and special cases." msgstr "" #: ../../faq/programming.rst:1771 #, fuzzy msgid "My class defines __del__ but it is not called when I delete the object." msgstr "我的類別定義了 __del__ 但是當我刪除物件時它沒有被呼叫。" #: ../../faq/programming.rst:1773 #, fuzzy msgid "There are several possible reasons for this." msgstr "這有幾個可能的原因。" #: ../../faq/programming.rst:1775 #, fuzzy msgid "" "The :keyword:`del` statement does not necessarily call :meth:`~object." "__del__` -- it simply decrements the object's reference count, and if this " "reaches zero :meth:`!__del__` is called." msgstr "" ":keyword:`del` 陳述式不一定呼叫 :meth:`~object.__del__` -- 它只是減少物件的引" "用計數,如果達到零,則呼叫 :meth:`!__del__`。" #: ../../faq/programming.rst:1779 #, fuzzy msgid "" "If your data structures contain circular links (e.g. a tree where each child " "has a parent reference and each parent has a list of children) the reference " "counts will never go back to zero. Once in a while Python runs an algorithm " "to detect such cycles, but the garbage collector might run some time after " "the last reference to your data structure vanishes, so your :meth:`!__del__` " "method may be called at an inconvenient and random time. This is " "inconvenient if you're trying to reproduce a problem. Worse, the order in " "which object's :meth:`!__del__` methods are executed is arbitrary. You can " "run :func:`gc.collect` to force a collection, but there *are* pathological " "cases where objects will never be collected." msgstr "" "如果你的資料結構包含循環鏈接(例如,一棵樹,其中每個子項都有一個父項參照,每" "個父項都有一個子項list),參照計數將永遠不會回到零。 Python 偶爾會運行一種演" "算法來檢測此類別循環,但垃圾收集器可能會在對你的資料結構的最後一次參照消失後" "運行一段時間,因此你的 :meth:`!__del__` 方法可能會在不方便且隨機的時間呼叫.如" "果你試圖重現問題,這會很不方便。更糟糕的是,物件的 :meth:`!__del__` 方法的執" "行順序是任意的。你可以運行 :func:`gc.collect` 來強制收集,但*存在*永遠不會收" "集物件的病態情況。" #: ../../faq/programming.rst:1790 #, fuzzy msgid "" "Despite the cycle collector, it's still a good idea to define an explicit " "``close()`` method on objects to be called whenever you're done with them. " "The ``close()`` method can then remove attributes that refer to subobjects. " "Don't call :meth:`!__del__` directly -- :meth:`!__del__` should call " "``close()`` and ``close()`` should make sure that it can be called more than " "once for the same object." msgstr "" "儘管有循環收集器,但在物件上定義一個顯式的 ``close()`` 方法仍然是一個好主意," "以便在你完成使用它們時呼叫它們。然後,``close()`` 方法可以刪除參照子物件的屬" "性。不要直接呼叫 :meth:`!__del__` -- :meth:`!__del__` 應該呼叫 ``close()`` 並" "且 ``close()`` 應該確保它可以多次呼叫同一個物件。" #: ../../faq/programming.rst:1797 #, fuzzy msgid "" "Another way to avoid cyclical references is to use the :mod:`weakref` " "module, which allows you to point to objects without incrementing their " "reference count. Tree data structures, for instance, should use weak " "references for their parent and sibling references (if they need them!)." msgstr "" "另一種避免循環參照的方法是使用 :mod:`weakref` 模組,它允許你在不增加參照計數" "的情況下指向物件。例如,樹資料結構應該對其父參照和同級參照使用弱參照(如果需" "要的話!)。" #: ../../faq/programming.rst:1810 #, fuzzy msgid "" "Finally, if your :meth:`!__del__` method raises an exception, a warning " "message is printed to :data:`sys.stderr`." msgstr "" "最後,如果你的 :meth:`!__del__` 方法引發例外,則會將一條警告消息印出到 :data:" "`sys.stderr`。" #: ../../faq/programming.rst:1815 #, fuzzy msgid "How do I get a list of all instances of a given class?" msgstr "如何獲取給定類別的所有實例的 list?" #: ../../faq/programming.rst:1817 #, fuzzy msgid "" "Python does not keep track of all instances of a class (or of a built-in " "type). You can program the class's constructor to keep track of all " "instances by keeping a list of weak references to each instance." msgstr "" "Python 不會跟踪類別(或內建型別)的所有實例。你可以對類別的構造函式進行編程," "以透過保留對每個實例的弱參照list來跟踪所有實例。" #: ../../faq/programming.rst:1823 #, fuzzy msgid "Why does the result of ``id()`` appear to be not unique?" msgstr "為什麼 ``id()`` 的結果看起來不唯一?" #: ../../faq/programming.rst:1825 #, fuzzy msgid "" "The :func:`id` builtin returns an integer that is guaranteed to be unique " "during the lifetime of the object. Since in CPython, this is the object's " "memory address, it happens frequently that after an object is deleted from " "memory, the next freshly created object is allocated at the same position in " "memory. This is illustrated by this example:" msgstr "" ":func:`id` 內建函式回傳一個整數,保證在物件的生命週期內是唯一的。因為在 " "CPython 中,這是物件的記憶體地址,所以經常發生在從記憶體中刪除一個物件後,下" "一個新建立的物件被分配在記憶體中的相同位置。這個例子說明了這一點:" #: ../../faq/programming.rst:1836 #, fuzzy msgid "" "The two ids belong to different integer objects that are created before, and " "deleted immediately after execution of the ``id()`` call. To be sure that " "objects whose id you want to examine are still alive, create another " "reference to the object:" msgstr "" "這兩個 id 屬於之前建立的不同整數物件,並在執行 ``id()`` 呼叫後立即刪除。要確" "保你要檢查其 id 的物件仍然存在,請建立對該物件的另一個參照:" #: ../../faq/programming.rst:1849 msgid "When can I rely on identity tests with the *is* operator?" msgstr "我什麼時候可以依靠 *is* 運算子進行識別性測試?" #: ../../faq/programming.rst:1851 msgid "" "The ``is`` operator tests for object identity. The test ``a is b`` is " "equivalent to ``id(a) == id(b)``." msgstr "" "``is`` 運算子測試物件識別性。測試 ``a is b`` 等同於 ``id(a) == id(b)`` 。" #: ../../faq/programming.rst:1854 msgid "" "The most important property of an identity test is that an object is always " "identical to itself, ``a is a`` always returns ``True``. Identity tests are " "usually faster than equality tests. And unlike equality tests, identity " "tests are guaranteed to return a boolean ``True`` or ``False``." msgstr "" "識別性測試最重要的屬性是物件始終與自身相同, ``a is a`` 總是回傳 ``True`` 。" "識別性測試通常比相等性測試更快。與相等性測試不同,識別性測試保證回傳布林值 " "``True`` 或 ``False`` 。" #: ../../faq/programming.rst:1859 msgid "" "However, identity tests can *only* be substituted for equality tests when " "object identity is assured. Generally, there are three circumstances where " "identity is guaranteed:" msgstr "" "然而,*只有*\\ 當物件識別性得到保證時,識別性測試才能代替相等性測試。一般來" "說,保證識別性的情況有以下三種:" #: ../../faq/programming.rst:1863 msgid "" "1) Assignments create new names but do not change object identity. After " "the assignment ``new = old``, it is guaranteed that ``new is old``." msgstr "" "1) 賦值建立新名稱但不改變物件識別性。賦值 ``new = old`` 後,保證 ``new is " "old``。" #: ../../faq/programming.rst:1866 msgid "" "2) Putting an object in a container that stores object references does not " "change object identity. After the list assignment ``s[0] = x``, it is " "guaranteed that ``s[0] is x``." msgstr "" "2) 將物件放入存儲物件參照的容器中不會改變物件識別性。在 list 賦值 ``s[0] = " "x`` 之後,保證 ``s[0] 是 x``。" #: ../../faq/programming.rst:1870 #, fuzzy msgid "" "3) If an object is a singleton, it means that only one instance of that " "object can exist. After the assignments ``a = None`` and ``b = None``, it " "is guaranteed that ``a is b`` because ``None`` is a singleton." msgstr "" "3)如果一個物件是單例,則意味著該物件只能存在一個實例。在賦值 ``a = None`` " "和 ``b = None`` 之後,可以保證 ``a is b`` 因為 ``None`` 是單例。" #: ../../faq/programming.rst:1874 msgid "" "In most other circumstances, identity tests are inadvisable and equality " "tests are preferred. In particular, identity tests should not be used to " "check constants such as :class:`int` and :class:`str` which aren't " "guaranteed to be singletons::" msgstr "" "在大多數其他情況下,識別性測試是不可取的,相等性測試是首選。特別是,識別性測" "試不應用於檢查常數,例如不能保證是單例的 :class:`int` 和 :class:`str`: ::" #: ../../faq/programming.rst:1879 msgid "" ">>> a = 1000\n" ">>> b = 500\n" ">>> c = b + 500\n" ">>> a is c\n" "False\n" "\n" ">>> a = 'Python'\n" ">>> b = 'Py'\n" ">>> c = b + 'thon'\n" ">>> a is c\n" "False" msgstr "" ">>> a = 1000\n" ">>> b = 500\n" ">>> c = b + 500\n" ">>> a is c\n" "False\n" "\n" ">>> a = 'Python'\n" ">>> b = 'Py'\n" ">>> c = b + 'thon'\n" ">>> a is c\n" "False" #: ../../faq/programming.rst:1891 #, fuzzy msgid "Likewise, new instances of mutable containers are never identical::" msgstr "同樣,可變容器的新實例永遠不會相同: ::" #: ../../faq/programming.rst:1893 msgid "" ">>> a = []\n" ">>> b = []\n" ">>> a is b\n" "False" msgstr "" ">>> a = []\n" ">>> b = []\n" ">>> a is b\n" "False" #: ../../faq/programming.rst:1898 msgid "" "In the standard library code, you will see several common patterns for " "correctly using identity tests:" msgstr "在標準函式庫程式碼中,你將看到幾種正確使用識別性測試的常見模式:" #: ../../faq/programming.rst:1901 msgid "" "1) As recommended by :pep:`8`, an identity test is the preferred way to " "check for ``None``. This reads like plain English in code and avoids " "confusion with other objects that may have boolean values that evaluate to " "false." msgstr "" "1) 正如 :pep:`8` 所推薦的,識別性測試是檢查 ``None`` 的首選方法。這在程式碼中" "讀起來像簡單的英語,並避免與其他可能具有評估為 false 的布林值的物件混淆。" #: ../../faq/programming.rst:1905 #, fuzzy msgid "" "2) Detecting optional arguments can be tricky when ``None`` is a valid input " "value. In those situations, you can create a singleton sentinel object " "guaranteed to be distinct from other objects. For example, here is how to " "implement a method that behaves like :meth:`dict.pop`::" msgstr "" "2)當 ``None`` 是有效輸入值時,檢測可選引數可能會很棘手。在這些情況下,你可以" "建立一個保證與其他物件不同的單例哨兵物件。例如,這裡是如何實作一個行為類似" "於 :meth:`dict.pop` 的方法: ::" #: ../../faq/programming.rst:1910 msgid "" "_sentinel = object()\n" "\n" "def pop(self, key, default=_sentinel):\n" " if key in self:\n" " value = self[key]\n" " del self[key]\n" " return value\n" " if default is _sentinel:\n" " raise KeyError(key)\n" " return default" msgstr "" "_sentinel = object()\n" "\n" "def pop(self, key, default=_sentinel):\n" " if key in self:\n" " value = self[key]\n" " del self[key]\n" " return value\n" " if default is _sentinel:\n" " raise KeyError(key)\n" " return default" #: ../../faq/programming.rst:1921 msgid "" "3) Container implementations sometimes need to augment equality tests with " "identity tests. This prevents the code from being confused by objects such " "as ``float('NaN')`` that are not equal to themselves." msgstr "" "3) 容器實作有時需要透過識別性測試來增強相等性測試。這可以防止程式碼被諸如 " "float('NaN') 之類的不等於自身的物件所混淆。" #: ../../faq/programming.rst:1925 msgid "" "For example, here is the implementation of :meth:`!collections.abc.Sequence." "__contains__`::" msgstr "" "例如,以下是 :meth:`!collections.abc.Sequence.__contains__` 的實作: ::" #: ../../faq/programming.rst:1928 msgid "" "def __contains__(self, value):\n" " for v in self:\n" " if v is value or v == value:\n" " return True\n" " return False" msgstr "" "def __contains__(self, value):\n" " for v in self:\n" " if v is value or v == value:\n" " return True\n" " return False" #: ../../faq/programming.rst:1936 msgid "" "How can a subclass control what data is stored in an immutable instance?" msgstr "子類別如何控制不可變實例中存儲的資料?" #: ../../faq/programming.rst:1938 #, fuzzy msgid "" "When subclassing an immutable type, override the :meth:`~object.__new__` " "method instead of the :meth:`~object.__init__` method. The latter only runs " "*after* an instance is created, which is too late to alter data in an " "immutable instance." msgstr "" "當對不可變型別進行子類別化時,覆蓋 :meth:`~object.__new__` 方法而不是 :meth:" "`~object.__init__` 方法。後者僅在*建立實例後*運行,這為時已晚,無法更改不可變" "實例中的資料。" #: ../../faq/programming.rst:1943 #, fuzzy msgid "" "All of these immutable classes have a different signature than their parent " "class:" msgstr "所有這些不可變類別都具有與其父類別不同的簽名:" #: ../../faq/programming.rst:1946 msgid "" "from datetime import date\n" "\n" "class FirstOfMonthDate(date):\n" " \"Always choose the first day of the month\"\n" " def __new__(cls, year, month, day):\n" " return super().__new__(cls, year, month, 1)\n" "\n" "class NamedInt(int):\n" " \"Allow text names for some numbers\"\n" " xlat = {'zero': 0, 'one': 1, 'ten': 10}\n" " def __new__(cls, value):\n" " value = cls.xlat.get(value, value)\n" " return super().__new__(cls, value)\n" "\n" "class TitleStr(str):\n" " \"Convert str to name suitable for a URL path\"\n" " def __new__(cls, s):\n" " s = s.lower().replace(' ', '-')\n" " s = ''.join([c for c in s if c.isalnum() or c == '-'])\n" " return super().__new__(cls, s)" msgstr "" #: ../../faq/programming.rst:1969 msgid "The classes can be used like this:" msgstr "這些類別可以像這樣使用:" #: ../../faq/programming.rst:1971 msgid "" ">>> FirstOfMonthDate(2012, 2, 14)\n" "FirstOfMonthDate(2012, 2, 1)\n" ">>> NamedInt('ten')\n" "10\n" ">>> NamedInt(20)\n" "20\n" ">>> TitleStr('Blog: Why Python Rocks')\n" "'blog-why-python-rocks'" msgstr "" ">>> FirstOfMonthDate(2012, 2, 14)\n" "FirstOfMonthDate(2012, 2, 1)\n" ">>> NamedInt('ten')\n" "10\n" ">>> NamedInt(20)\n" "20\n" ">>> TitleStr('Blog: Why Python Rocks')\n" "'blog-why-python-rocks'" #: ../../faq/programming.rst:1986 msgid "How do I cache method calls?" msgstr "如何快取方法呼叫?" #: ../../faq/programming.rst:1988 #, fuzzy msgid "" "The two principal tools for caching methods are :func:`functools." "cached_property` and :func:`functools.lru_cache`. The former stores results " "at the instance level and the latter at the class level." msgstr "" "快取方法的兩個主要工具是 func:`functools.cached_property` 和 :func:" "`functools.lru_cache`。前者在實例級別存儲結果,後者在類別級別存儲結果。" #: ../../faq/programming.rst:1993 #, fuzzy msgid "" "The *cached_property* approach only works with methods that do not take any " "arguments. It does not create a reference to the instance. The cached " "method result will be kept only as long as the instance is alive." msgstr "" "*cached_property* 方法僅適用於不帶任何引數的方法。它不會建立對實例的參照。只" "要實例還活著,快取的方法結果就會被保留。" #: ../../faq/programming.rst:1997 #, fuzzy msgid "" "The advantage is that when an instance is no longer used, the cached method " "result will be released right away. The disadvantage is that if instances " "accumulate, so too will the accumulated method results. They can grow " "without bound." msgstr "" "好處是當一個實例不再使用時,快取的方法結果會立即釋放。缺點是如果實例累積,累" "積的方法結果也會累積。他們可以不受限制地成長。" #: ../../faq/programming.rst:2002 msgid "" "The *lru_cache* approach works with methods that have :term:`hashable` " "arguments. It creates a reference to the instance unless special efforts " "are made to pass in weak references." msgstr "" "*lru_cache* 方法適用於具有\\ :term:`可雜湊 `\\ 引數的方法。除非特別" "努力傳遞弱參照,否則它會建立對實例的參照。" #: ../../faq/programming.rst:2006 #, fuzzy msgid "" "The advantage of the least recently used algorithm is that the cache is " "bounded by the specified *maxsize*. The disadvantage is that instances are " "kept alive until they age out of the cache or until the cache is cleared." msgstr "" "最近最少使用演算法的優點是快取受指定的 *maxsize* 限制。缺點是實例會一直保持活" "動狀態,直到它們從快取中老化或快取被清除。" #: ../../faq/programming.rst:2011 msgid "This example shows the various techniques::" msgstr "這個例子展示了各種技術: ::" #: ../../faq/programming.rst:2013 msgid "" "class Weather:\n" " \"Lookup weather information on a government website\"\n" "\n" " def __init__(self, station_id):\n" " self._station_id = station_id\n" " # The _station_id is private and immutable\n" "\n" " def current_temperature(self):\n" " \"Latest hourly observation\"\n" " # Do not cache this because old results\n" " # can be out of date.\n" "\n" " @cached_property\n" " def location(self):\n" " \"Return the longitude/latitude coordinates of the station\"\n" " # Result only depends on the station_id\n" "\n" " @lru_cache(maxsize=20)\n" " def historic_rainfall(self, date, units='mm'):\n" " \"Rainfall on a given date\"\n" " # Depends on the station_id, date, and units." msgstr "" #: ../../faq/programming.rst:2035 #, fuzzy msgid "" "The above example assumes that the *station_id* never changes. If the " "relevant instance attributes are mutable, the *cached_property* approach " "can't be made to work because it cannot detect changes to the attributes." msgstr "" "上面的例子假設 *station_id* 永遠不會改變。如果相關的實例屬性是可變的,則 " "*cached_property* 方法無法工作,因為它無法檢測到屬性的更改。" #: ../../faq/programming.rst:2040 #, fuzzy msgid "" "To make the *lru_cache* approach work when the *station_id* is mutable, the " "class needs to define the :meth:`~object.__eq__` and :meth:`~object." "__hash__` methods so that the cache can detect relevant attribute updates::" msgstr "" "要在 *station_id* 可變時使 *lru_cache* 方法起作用,該類別需要定義 :meth:" "`~object.__eq__` 和 :meth:`~object.__hash__` 方法,以便快取可以檢測相關屬性更" "新: ::" #: ../../faq/programming.rst:2044 msgid "" "class Weather:\n" " \"Example with a mutable station identifier\"\n" "\n" " def __init__(self, station_id):\n" " self.station_id = station_id\n" "\n" " def change_station(self, station_id):\n" " self.station_id = station_id\n" "\n" " def __eq__(self, other):\n" " return self.station_id == other.station_id\n" "\n" " def __hash__(self):\n" " return hash(self.station_id)\n" "\n" " @lru_cache(maxsize=20)\n" " def historic_rainfall(self, date, units='cm'):\n" " 'Rainfall on a given date'\n" " # Depends on the station_id, date, and units." msgstr "" #: ../../faq/programming.rst:2066 msgid "Modules" msgstr "模組" #: ../../faq/programming.rst:2069 msgid "How do I create a .pyc file?" msgstr "如何建立 .pyc 檔案?" #: ../../faq/programming.rst:2071 #, fuzzy msgid "" "When a module is imported for the first time (or when the source file has " "changed since the current compiled file was created) a ``.pyc`` file " "containing the compiled code should be created in a ``__pycache__`` " "subdirectory of the directory containing the ``.py`` file. The ``.pyc`` " "file will have a filename that starts with the same name as the ``.py`` " "file, and ends with ``.pyc``, with a middle component that depends on the " "particular ``python`` binary that created it. (See :pep:`3147` for details.)" msgstr "" "第一次引入模組時(或者源檔案自建立當前編譯檔案後發生更改時)應在 " "``__pycache__`` 的子目錄中建立包含編譯程式碼的 ``.pyc`` 檔案包含 .py 檔案的目" "錄。 ``.pyc`` 檔案的檔案名以與``.py`` 檔案相同的名稱開頭,以``.pyc`` 結尾,中" "間部分依賴於特定的``python `` 建立它的二進製檔案。(有關詳細資訊,請參閱 :" "pep:`3147`。)" #: ../../faq/programming.rst:2079 #, fuzzy msgid "" "One reason that a ``.pyc`` file may not be created is a permissions problem " "with the directory containing the source file, meaning that the " "``__pycache__`` subdirectory cannot be created. This can happen, for " "example, if you develop as one user but run as another, such as if you are " "testing with a web server." msgstr "" "無法建立 .pyc 檔案的原因之一是包含源檔案的目錄存在權限問題,這意味著無法建立 " "__pycache__ 子目錄。例如,如果你以一個使用者的身份開發但以另一個使用者的身份" "運行,例如你正在使用 Web 服務器進行測試,就會發生這種情況。" #: ../../faq/programming.rst:2084 #, fuzzy msgid "" "Unless the :envvar:`PYTHONDONTWRITEBYTECODE` environment variable is set, " "creation of a .pyc file is automatic if you're importing a module and Python " "has the ability (permissions, free space, etc...) to create a " "``__pycache__`` subdirectory and write the compiled module to that " "subdirectory." msgstr "" "除非:envvar:`PYTHONDONTWRITEBYTECODE` 環境變數被設定,如果你正在引入一個模組" "並且 Python 有能力(權限,空閒空間等)建立一個 .pyc 檔案是自動的建立一個" "``__pycache__ `` 子目錄並將編譯後的模組寫入該子目錄。" #: ../../faq/programming.rst:2089 #, fuzzy msgid "" "Running Python on a top level script is not considered an import and no ``." "pyc`` will be created. For example, if you have a top-level module ``foo." "py`` that imports another module ``xyz.py``, when you run ``foo`` (by typing " "``python foo.py`` as a shell command), a ``.pyc`` will be created for " "``xyz`` because ``xyz`` is imported, but no ``.pyc`` file will be created " "for ``foo`` since ``foo.py`` isn't being imported." msgstr "" "在頂級腳本上運行 Python 不被視為引入,也不會建立 ``.pyc``。例如,如果你有一個" "頂級模組 ``foo.py`` 引入另一個模組 ``xyz.py`` ,當你運行 ``foo`` 時(透過輸" "入 ``python foo.py`` 作為一個 shell 命令),將為 xyz 建立一個 .pyc 因為引入" "了 xyz,但是不會為 foo 建立 .pyc 檔案,因為 ` `foo.py`` 沒有被引入。" #: ../../faq/programming.rst:2096 #, fuzzy msgid "" "If you need to create a ``.pyc`` file for ``foo`` -- that is, to create a ``." "pyc`` file for a module that is not imported -- you can, using the :mod:" "`py_compile` and :mod:`compileall` modules." msgstr "" "如果你需要為 ``foo`` 建立一個 ``.pyc`` 檔案——也就是說,為一個未引入的模組建立" "一個 ``.pyc`` 檔案——你可以使用 :mod :`py_compile` 和 :mod:`compileall` 模組。" #: ../../faq/programming.rst:2100 #, fuzzy msgid "" "The :mod:`py_compile` module can manually compile any module. One way is to " "use the ``compile()`` function in that module interactively::" msgstr "" ":mod:`py_compile` 模組可以手動編譯任何模組。一種方法是在該模組中以交互方式使" "用 ``compile()`` 函式: ::" #: ../../faq/programming.rst:2103 msgid "" ">>> import py_compile\n" ">>> py_compile.compile('foo.py') " msgstr "" ">>> import py_compile\n" ">>> py_compile.compile('foo.py') " #: ../../faq/programming.rst:2106 #, fuzzy msgid "" "This will write the ``.pyc`` to a ``__pycache__`` subdirectory in the same " "location as ``foo.py`` (or you can override that with the optional parameter " "``cfile``)." msgstr "" "這會將 .pyc 寫入與 foo.py 相同位置的 __pycache__ 子目錄(或者你可以使用可選參" "數 cfile 覆蓋它)。" #: ../../faq/programming.rst:2110 #, fuzzy msgid "" "You can also automatically compile all files in a directory or directories " "using the :mod:`compileall` module. You can do it from the shell prompt by " "running ``compileall.py`` and providing the path of a directory containing " "Python files to compile::" msgstr "" "你還可以使用 :mod:`compileall` 模組自動編譯目錄中的所有檔案。你可以在 shell " "提示符下運行 ``compileall.py`` 並提供包含要編譯的 Python 檔案的目錄路徑: ::" #: ../../faq/programming.rst:2115 msgid "python -m compileall ." msgstr "python -m compileall ." #: ../../faq/programming.rst:2119 msgid "How do I find the current module name?" msgstr "如何找到當前模組名稱?" #: ../../faq/programming.rst:2121 #, fuzzy msgid "" "A module can find out its own module name by looking at the predefined " "global variable ``__name__``. If this has the value ``'__main__'``, the " "program is running as a script. Many modules that are usually used by " "importing them also provide a command-line interface or a self-test, and " "only execute this code after checking ``__name__``::" msgstr "" "模組可以透過查看預定義的全域變數 ``__name__`` 來找出自己的模組名稱。如果它的" "值為``'__main__'``,則該程式作為腳本運行。許多通常透過引入使用的模組還提供命" "令行界面或自檢,只有在檢查 ``__name__`` 後才執行此程式碼: ::" #: ../../faq/programming.rst:2127 msgid "" "def main():\n" " print('Running test...')\n" " ...\n" "\n" "if __name__ == '__main__':\n" " main()" msgstr "" #: ../../faq/programming.rst:2136 #, fuzzy msgid "How can I have modules that mutually import each other?" msgstr "我怎樣才能擁有相互引入的模組?" #: ../../faq/programming.rst:2138 msgid "Suppose you have the following modules:" msgstr "假設你有以下模組:" #: ../../faq/programming.rst:2140 msgid ":file:`foo.py`::" msgstr ":file:`foo.py`: ::" #: ../../faq/programming.rst:2142 msgid "" "from bar import bar_var\n" "foo_var = 1" msgstr "" "from bar import bar_var\n" "foo_var = 1" #: ../../faq/programming.rst:2145 msgid ":file:`bar.py`::" msgstr ":file:`bar.py`: ::" #: ../../faq/programming.rst:2147 msgid "" "from foo import foo_var\n" "bar_var = 2" msgstr "" "from foo import foo_var\n" "bar_var = 2" #: ../../faq/programming.rst:2150 #, fuzzy msgid "The problem is that the interpreter will perform the following steps:" msgstr "問題是直譯器將執行以下步驟:" #: ../../faq/programming.rst:2152 #, fuzzy msgid "main imports ``foo``" msgstr "主要引入 ``foo``" #: ../../faq/programming.rst:2153 #, fuzzy msgid "Empty globals for ``foo`` are created" msgstr "建立了 ``foo`` 的空全域變數" #: ../../faq/programming.rst:2154 msgid "``foo`` is compiled and starts executing" msgstr "``foo`` 被編譯並開始執行" #: ../../faq/programming.rst:2155 msgid "``foo`` imports ``bar``" msgstr "``foo`` 引入 ``bar``" #: ../../faq/programming.rst:2156 #, fuzzy msgid "Empty globals for ``bar`` are created" msgstr "建立了 ``bar`` 的空全域變數" #: ../../faq/programming.rst:2157 msgid "``bar`` is compiled and starts executing" msgstr "``bar`` 已被編譯並開始執行" #: ../../faq/programming.rst:2158 #, fuzzy msgid "" "``bar`` imports ``foo`` (which is a no-op since there already is a module " "named ``foo``)" msgstr "" "``bar`` 引入 ``foo``(這是一個空操作,因為已經有一個名為 ``foo`` 的模組)" #: ../../faq/programming.rst:2159 #, fuzzy msgid "" "The import mechanism tries to read ``foo_var`` from ``foo`` globals, to set " "``bar.foo_var = foo.foo_var``" msgstr "" "引入機制嘗試從 ``foo`` 全域變數中讀取 ``foo_var`` ,以設定 ``bar.foo_var = " "foo.foo_var`` " #: ../../faq/programming.rst:2161 #, fuzzy msgid "" "The last step fails, because Python isn't done with interpreting ``foo`` yet " "and the global symbol dictionary for ``foo`` is still empty." msgstr "" "最後一步失敗了,因為 Python 還沒有完成對 ``foo`` 的直譯,而 ``foo`` 的全域符" "號字典仍然是空的。" #: ../../faq/programming.rst:2164 #, fuzzy msgid "" "The same thing happens when you use ``import foo``, and then try to access " "``foo.foo_var`` in global code." msgstr "" "當你使用 ``import foo``,然後嘗試在全域程式碼中存取 ``foo.foo_var`` 時,也會" "發生同樣的事情。" #: ../../faq/programming.rst:2167 msgid "There are (at least) three possible workarounds for this problem." msgstr "此問題有(至少)三種可能的解決方法。" #: ../../faq/programming.rst:2169 #, fuzzy msgid "" "Guido van Rossum recommends avoiding all uses of ``from import ..." "``, and placing all code inside functions. Initializations of global " "variables and class variables should use constants or built-in functions " "only. This means everything from an imported module is referenced as " "``.``." msgstr "" "Guido van Rossum 建議避免使用``from import ...``,並將所有程式碼放在" "函式中。全域變數和類別變數的初始化應該只使用常數或內建函式。這意味著來自引入" "模組的所有內容都被參照為 ``.``。" #: ../../faq/programming.rst:2174 msgid "" "Jim Roskind suggests performing steps in the following order in each module:" msgstr "Jim Roskind 建議在每個模組中按以下順序執行各個步驟:" #: ../../faq/programming.rst:2176 #, fuzzy msgid "" "exports (globals, functions, and classes that don't need imported base " "classes)" msgstr "導出(不需要引入基底類別的全域變數、函式和類別)" #: ../../faq/programming.rst:2178 msgid "``import`` statements" msgstr "``import`` 陳述式" #: ../../faq/programming.rst:2179 msgid "" "active code (including globals that are initialized from imported values)." msgstr "活躍程式碼(包括從引入值初始化的全域變數)。" #: ../../faq/programming.rst:2181 #, fuzzy msgid "" "Van Rossum doesn't like this approach much because the imports appear in a " "strange place, but it does work." msgstr "" "Van Rossum 不太喜歡這種方法,因為引入出現在一個奇怪的地方,但它確實有效。" #: ../../faq/programming.rst:2184 msgid "" "Matthias Urlichs recommends restructuring your code so that the recursive " "import is not necessary in the first place." msgstr "Matthias Urlichs 建議重構你的程式碼,以便打從一開始就不需要遞迴引入。" #: ../../faq/programming.rst:2187 msgid "These solutions are not mutually exclusive." msgstr "這些方案並不衝突。" #: ../../faq/programming.rst:2191 msgid "__import__('x.y.z') returns ; how do I get z?" msgstr "__import__('x.y.z') 回傳 ,那我怎麼得到 z?" #: ../../faq/programming.rst:2193 #, fuzzy msgid "" "Consider using the convenience function :func:`~importlib.import_module` " "from :mod:`importlib` instead::" msgstr "" "考慮使用來自 :mod:`importlib` 的便利函式 :func:`~importlib.import_module` 代" "替: ::" #: ../../faq/programming.rst:2196 msgid "z = importlib.import_module('x.y.z')" msgstr "z = importlib.import_module('x.y.z')" #: ../../faq/programming.rst:2200 msgid "" "When I edit an imported module and reimport it, the changes don't show up. " "Why does this happen?" msgstr "當我編輯需要引入的模組並重新引入它時,更動沒有反應出來。為什麼會這樣?" #: ../../faq/programming.rst:2202 #, fuzzy msgid "" "For reasons of efficiency as well as consistency, Python only reads the " "module file on the first time a module is imported. If it didn't, in a " "program consisting of many modules where each one imports the same basic " "module, the basic module would be parsed and re-parsed many times. To force " "re-reading of a changed module, do this::" msgstr "" "出於效率和一致性的原因,Python 僅在第一次引入模組時讀取模組檔案。如果沒有,在" "一個由許多模組組成的程式中,每個模組都引入相同的基本模組,基本模組將被解析和" "重新解析很多次。要強制重新讀取已更改的模組,請執行以下操作: ::" #: ../../faq/programming.rst:2208 msgid "" "import importlib\n" "import modname\n" "importlib.reload(modname)" msgstr "" "import importlib\n" "import modname\n" "importlib.reload(modname)" #: ../../faq/programming.rst:2212 #, fuzzy msgid "" "Warning: this technique is not 100% fool-proof. In particular, modules " "containing statements like ::" msgstr "警告:此技術並非 100% 萬無一失。尤其是,包含像這樣的陳述式的模組: ::" #: ../../faq/programming.rst:2215 msgid "from modname import some_objects" msgstr "from modname import some_objects" #: ../../faq/programming.rst:2217 #, fuzzy msgid "" "will continue to work with the old version of the imported objects. If the " "module contains class definitions, existing class instances will *not* be " "updated to use the new class definition. This can result in the following " "paradoxical behaviour::" msgstr "" "將繼續使用舊版本的引入物件。如果模組包含類別定義,現有的類別實例將*不會*更新" "為使用新的類別定義。這可能會導致以下自相矛盾的行為: ::" #: ../../faq/programming.rst:2222 msgid "" ">>> import importlib\n" ">>> import cls\n" ">>> c = cls.C() # Create an instance of C\n" ">>> importlib.reload(cls)\n" "\n" ">>> isinstance(c, cls.C) # isinstance is false?!?\n" "False" msgstr "" #: ../../faq/programming.rst:2230 msgid "" "The nature of the problem is made clear if you print out the \"identity\" of " "the class objects::" msgstr "如果印出類別物件的「識別性」,問題的本質就很清楚了: ::" #: ../../faq/programming.rst:2233 msgid "" ">>> hex(id(c.__class__))\n" "'0x7352a0'\n" ">>> hex(id(cls.C))\n" "'0x4198d0'" msgstr "" ">>> hex(id(c.__class__))\n" "'0x7352a0'\n" ">>> hex(id(cls.C))\n" "'0x4198d0'" #: ../../faq/programming.rst:408 msgid "argument" msgstr "argument(引數)" #: ../../faq/programming.rst:408 msgid "difference from parameter" msgstr "與 parameter(參數)的差異" #: ../../faq/programming.rst:408 msgid "parameter" msgstr "parameter(參數)" #: ../../faq/programming.rst:408 msgid "difference from argument" msgstr "與 argument(引數)的差異"