# Copyright (C) 2001 Python Software Foundation # This file is distributed under the same license as the Python package. # # Translators: # jerrychen , 2016 # Adrian Liaw , 2018 # Steven Hsu , 2021-2022 # Phil Lin , 2022 msgid "" msgstr "" "Project-Id-Version: Python 3.14\n" "Report-Msgid-Bugs-To: \n" "POT-Creation-Date: 2025-07-22 00:17+0000\n" "PO-Revision-Date: 2022-10-23 20:30+0800\n" "Last-Translator: Phil Lin \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.2\n" #: ../../tutorial/modules.rst:5 msgid "Modules" msgstr "模組 (Module)" #: ../../tutorial/modules.rst:7 msgid "" "If you quit from the Python interpreter and enter it again, the definitions " "you have made (functions and variables) are lost. Therefore, if you want to " "write a somewhat longer program, you are better off using a text editor to " "prepare the input for the interpreter and running it with that file as input " "instead. This is known as creating a *script*. As your program gets " "longer, you may want to split it into several files for easier maintenance. " "You may also want to use a handy function that you've written in several " "programs without copying its definition into each program." msgstr "" "如果從 Python 直譯器離開後又再次進入,之前(幫函式或變數)做的定義都會消失。" "因此,想要寫一些比較長的程式時,你最好使用編輯器來準備要輸入給直譯器的內容," "並且用該檔案來運行它。這就是一個\\ *腳本 (script)*。隨著你的程式越變越長,你" "可能會想要把它分開成幾個檔案,讓它比較好維護。你可能也會想用一個你之前已經在" "其他程式寫好的函式,但不想要複製該函式的原始定義到所有使用它的程式裡。" #: ../../tutorial/modules.rst:16 msgid "" "To support this, Python has a way to put definitions in a file and use them " "in a script or in an interactive instance of the interpreter. Such a file is " "called a *module*; definitions from a module can be *imported* into other " "modules or into the *main* module (the collection of variables that you have " "access to in a script executed at the top level and in calculator mode)." msgstr "" "為了支援這一點,Python 有一種方法可以將定義放入檔案中,並在互動模式下的直譯器" "中使用它們。這種檔案稱為\\ *模組 (module)*;模組中的定義可以被 *import* 到其" "他模組中,或是被 *import* 至\\ *主 (main)* 模組(在最頂層執行的腳本,以及互動" "模式下,所使用的變數集合)。" #: ../../tutorial/modules.rst:22 msgid "" "A module is a file containing Python definitions and statements. The file " "name is the module name with the suffix :file:`.py` appended. Within a " "module, the module's name (as a string) is available as the value of the " "global variable ``__name__``. For instance, use your favorite text editor " "to create a file called :file:`fibo.py` in the current directory with the " "following contents::" msgstr "" "模組是指包含 Python 定義和語句的檔案,檔案名稱是模組名稱加上 :file:`.py`。在" "模組中,模組的名稱(作為字串)會是全域變數 ``__name__`` 的值。例如,用你喜歡" "的文字編輯器在資料夾中創一個名為 :file:`fibo.py` 的檔案,內容如下: ::" #: ../../tutorial/modules.rst:28 msgid "" "# Fibonacci numbers module\n" "\n" "def fib(n):\n" " \"\"\"Write Fibonacci series up to n.\"\"\"\n" " a, b = 0, 1\n" " while a < n:\n" " print(a, end=' ')\n" " a, b = b, a+b\n" " print()\n" "\n" "def fib2(n):\n" " \"\"\"Return Fibonacci series up to n.\"\"\"\n" " result = []\n" " a, b = 0, 1\n" " while a < n:\n" " result.append(a)\n" " a, b = b, a+b\n" " return result" msgstr "" "# 費波那契數模組\n" "\n" "def fib(n):\n" " \"\"\"寫出費波那契數列至第 n 位。\"\"\"\n" " a, b = 0, 1\n" " while a < n:\n" " print(a, end=' ')\n" " a, b = b, a+b\n" " print()\n" "\n" "def fib2(n):\n" " \"\"\"回傳費波那契數列至第 n 位。\"\"\"\n" " result = []\n" " a, b = 0, 1\n" " while a < n:\n" " result.append(a)\n" " a, b = b, a+b\n" " return result" #: ../../tutorial/modules.rst:47 msgid "" "Now enter the Python interpreter and import this module with the following " "command::" msgstr "現在進入 Python 直譯器並用以下指令 import 這個模組: ::" #: ../../tutorial/modules.rst:50 msgid ">>> import fibo" msgstr ">>> import fibo" #: ../../tutorial/modules.rst:52 msgid "" "This does not add the names of the functions defined in ``fibo`` directly " "to the current :term:`namespace` (see :ref:`tut-scopes` for more details); " "it only adds the module name ``fibo`` there. Using the module name you can " "access the functions::" msgstr "" "這並不會將 ``fibo`` 中定義的函式名稱直接加入目前的 :term:`namespace` 中(詳情" "請見 :ref:`tut-scopes`);它只會加入 ``fibo`` 的模組名稱。使用此模組名稱,就" "可以存取函式: ::" #: ../../tutorial/modules.rst:57 msgid "" ">>> fibo.fib(1000)\n" "0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987\n" ">>> fibo.fib2(100)\n" "[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]\n" ">>> fibo.__name__\n" "'fibo'" msgstr "" ">>> fibo.fib(1000)\n" "0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987\n" ">>> fibo.fib2(100)\n" "[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]\n" ">>> fibo.__name__\n" "'fibo'" #: ../../tutorial/modules.rst:64 msgid "" "If you intend to use a function often you can assign it to a local name::" msgstr "如果你打算經常使用其中某個函式,可以將其指定至區域變數: ::" #: ../../tutorial/modules.rst:66 msgid "" ">>> fib = fibo.fib\n" ">>> fib(500)\n" "0 1 1 2 3 5 8 13 21 34 55 89 144 233 377" msgstr "" ">>> fib = fibo.fib\n" ">>> fib(500)\n" "0 1 1 2 3 5 8 13 21 34 55 89 144 233 377" #: ../../tutorial/modules.rst:74 msgid "More on Modules" msgstr "深入了解模組" #: ../../tutorial/modules.rst:76 msgid "" "A module can contain executable statements as well as function definitions. " "These statements are intended to initialize the module. They are executed " "only the *first* time the module name is encountered in an import statement. " "[#]_ (They are also run if the file is executed as a script.)" msgstr "" "模組可以包含可執行的陳述式以及函式的定義。這些陳述式是作為模組的初始化,它們" "只會在\\ *第一次*\\ 被 import 時才會執行。[#]_\\ (如果檔案被當成腳本執行,也" "會執行它們)。" #: ../../tutorial/modules.rst:81 msgid "" "Each module has its own private namespace, which is used as the global " "namespace by all functions defined in the module. Thus, the author of a " "module can use global variables in the module without worrying about " "accidental clashes with a user's global variables. On the other hand, if you " "know what you are doing you can touch a module's global variables with the " "same notation used to refer to its functions, ``modname.itemname``." msgstr "" "每個模組都有它自己的私有命名空間 (namespace),模組內定義的函式會把該模組的私" "有符號表當成全域命名空間使用。因此,模組的作者可以在模組中使用全域變數,而不" "必擔心和使用者的全域變數發生意外的名稱衝突。另一方面,如果你知道自己在做什" "麼,你可以用這個方式取用模組的全域變數,以和引用函式一樣的寫法,``modname." "itemname``。" #: ../../tutorial/modules.rst:88 msgid "" "Modules can import other modules. It is customary but not required to place " "all :keyword:`import` statements at the beginning of a module (or script, " "for that matter). The imported module names, if placed at the top level of " "a module (outside any functions or classes), are added to the module's " "global namespace." msgstr "" "在一個模組中可以 import 其他模組。把所有的 :keyword:`import` 陳述式放在模組" "(就這邊來說,腳本也是一樣)的最開頭是個慣例,但並沒有強制。如放置在模組的最" "高層(不在任何函式或 class 中),被 import 的模組名稱將被加入全域命名空間中。" #: ../../tutorial/modules.rst:93 msgid "" "There is a variant of the :keyword:`import` statement that imports names " "from a module directly into the importing module's namespace. For example::" msgstr "" ":keyword:`import` 陳述式有另一種變形寫法,可以直接將名稱從欲 import 的模組," "直接 import 至原模組的命名空間中。例如: ::" #: ../../tutorial/modules.rst:96 msgid "" ">>> from fibo import fib, fib2\n" ">>> fib(500)\n" "0 1 1 2 3 5 8 13 21 34 55 89 144 233 377" msgstr "" ">>> from fibo import fib, fib2\n" ">>> fib(500)\n" "0 1 1 2 3 5 8 13 21 34 55 89 144 233 377" #: ../../tutorial/modules.rst:100 msgid "" "This does not introduce the module name from which the imports are taken in " "the local namespace (so in the example, ``fibo`` is not defined)." msgstr "" "在 import 之後的名稱會被導入,但定義該函式的整個模組名稱並不會被引入在區域命" "名空間中(因此,示例中的 ``fibo`` 未被定義)。" #: ../../tutorial/modules.rst:103 msgid "There is even a variant to import all names that a module defines::" msgstr "甚至還有另一種變形寫法,可以 import 模組定義的所有名稱: ::" #: ../../tutorial/modules.rst:105 msgid "" ">>> from fibo import *\n" ">>> fib(500)\n" "0 1 1 2 3 5 8 13 21 34 55 89 144 233 377" msgstr "" ">>> from fibo import *\n" ">>> fib(500)\n" "0 1 1 2 3 5 8 13 21 34 55 89 144 233 377" #: ../../tutorial/modules.rst:109 msgid "" "This imports all names except those beginning with an underscore (``_``). In " "most cases Python programmers do not use this facility since it introduces " "an unknown set of names into the interpreter, possibly hiding some things " "you have already defined." msgstr "" "這個寫法會 import 模組中所有的名稱,除了使用底線 (``_``) 開頭的名稱。大多數情" "況下,Python 程式設計師不大使用這個功能,因為它在直譯器中引入了一組未知的名" "稱,並且可能覆蓋了某些你已經定義的內容。" #: ../../tutorial/modules.rst:114 msgid "" "Note that in general the practice of importing ``*`` from a module or " "package is frowned upon, since it often causes poorly readable code. " "However, it is okay to use it to save typing in interactive sessions." msgstr "" "請注意,一般情況下並不建議從模組或套件中 import ``*`` 的做法,因為它通常會導" "致可讀性較差的程式碼。但若是使用它來在互動模式中節省打字時間,則是可以接受" "的。" #: ../../tutorial/modules.rst:118 msgid "" "If the module name is followed by :keyword:`!as`, then the name following :" "keyword:`!as` is bound directly to the imported module." msgstr "" "如果模組名稱後面出現 :keyword:`!as`,則 :keyword:`!as` 之後的名稱將直接和被 " "import 模組綁定在一起。" #: ../../tutorial/modules.rst:123 msgid "" ">>> import fibo as fib\n" ">>> fib.fib(500)\n" "0 1 1 2 3 5 8 13 21 34 55 89 144 233 377" msgstr "" ">>> import fibo as fib\n" ">>> fib.fib(500)\n" "0 1 1 2 3 5 8 13 21 34 55 89 144 233 377" #: ../../tutorial/modules.rst:127 msgid "" "This is effectively importing the module in the same way that ``import " "fibo`` will do, with the only difference of it being available as ``fib``." msgstr "" "這個 import 方式和 ``import fibo`` 實質上是一樣的,唯一的差別是現在要用 " "``fib`` 使用模組。" #: ../../tutorial/modules.rst:130 msgid "" "It can also be used when utilising :keyword:`from` with similar effects::" msgstr "在使用 :keyword:`from` 時也可以用同樣的方式獲得類似的效果: ::" #: ../../tutorial/modules.rst:132 msgid "" ">>> from fibo import fib as fibonacci\n" ">>> fibonacci(500)\n" "0 1 1 2 3 5 8 13 21 34 55 89 144 233 377" msgstr "" ">>> from fibo import fib as fibonacci\n" ">>> fibonacci(500)\n" "0 1 1 2 3 5 8 13 21 34 55 89 144 233 377" #: ../../tutorial/modules.rst:139 msgid "" "For efficiency reasons, each module is only imported once per interpreter " "session. Therefore, if you change your modules, you must restart the " "interpreter -- or, if it's just one module you want to test interactively, " "use :func:`importlib.reload`, e.g. ``import importlib; importlib." "reload(modulename)``." msgstr "" "出於效率原因,每個模組在每個直譯器 session 中僅會被 import 一次。因此,如果你" "更改了模組,則必須重啟直譯器——或者,如果只是一個想要在互動模式下測試的模組," "可以使用 :func:`importlib.reload`。例如:``import importlib; importlib." "reload(modulename)``。" #: ../../tutorial/modules.rst:149 msgid "Executing modules as scripts" msgstr "把模組當作腳本執行" #: ../../tutorial/modules.rst:151 msgid "When you run a Python module with ::" msgstr "當使用以下內容運行 Python 模組時: ::" #: ../../tutorial/modules.rst:153 msgid "python fibo.py " msgstr "python fibo.py " #: ../../tutorial/modules.rst:155 msgid "" "the code in the module will be executed, just as if you imported it, but " "with the ``__name__`` set to ``\"__main__\"``. That means that by adding " "this code at the end of your module::" msgstr "" "如同使用 import 指令,模組中的程式碼會被執行,但 ``__name__`` 被設為 " "``\"__main__\"``。這意味著,透過在模組的末尾添加以下程式碼: ::" #: ../../tutorial/modules.rst:159 msgid "" "if __name__ == \"__main__\":\n" " import sys\n" " fib(int(sys.argv[1]))" msgstr "" "if __name__ == \"__main__\":\n" " import sys\n" " fib(int(sys.argv[1]))" #: ../../tutorial/modules.rst:163 msgid "" "you can make the file usable as a script as well as an importable module, " "because the code that parses the command line only runs if the module is " "executed as the \"main\" file:" msgstr "" "你可以將檔案作為腳本也同時可以作為被 import 的模組,因為剖析 (parse) 命令列的" "程式碼只會在當模組是「主」檔案時,才會執行:" #: ../../tutorial/modules.rst:167 msgid "" "$ python fibo.py 50\n" "0 1 1 2 3 5 8 13 21 34" msgstr "" "$ python fibo.py 50\n" "0 1 1 2 3 5 8 13 21 34" #: ../../tutorial/modules.rst:172 msgid "If the module is imported, the code is not run::" msgstr "如果此模組是被 import 的,則該段程式碼不會被執行: ::" #: ../../tutorial/modules.rst:174 msgid "" ">>> import fibo\n" ">>>" msgstr "" ">>> import fibo\n" ">>>" #: ../../tutorial/modules.rst:177 msgid "" "This is often used either to provide a convenient user interface to a " "module, or for testing purposes (running the module as a script executes a " "test suite)." msgstr "" "這通常是用來為模組提供方便的使用者介面,或者用於測試目的(執行測試套件時,以" "腳本的方式執行模組)。" #: ../../tutorial/modules.rst:184 msgid "The Module Search Path" msgstr "模組的搜尋路徑" #: ../../tutorial/modules.rst:188 msgid "" "When a module named :mod:`!spam` is imported, the interpreter first searches " "for a built-in module with that name. These module names are listed in :data:" "`sys.builtin_module_names`. If not found, it then searches for a file named :" "file:`spam.py` in a list of directories given by the variable :data:`sys." "path`. :data:`sys.path` is initialized from these locations:" msgstr "" "Import 一個名為 :mod:`!spam` 的模組時,直譯器首先會搜尋具有該名稱的內建模組。" "模組名稱列在 :data:`sys.builtin_module_names` 當中。如果找不到,接下來會在變" "數 :data:`sys.path` 所給定的資料夾清單之中,搜尋一個名為 :file:`spam.py` 的檔" "案。:data:`sys.path` 從這些位置開始進行初始化:" #: ../../tutorial/modules.rst:194 msgid "" "The directory containing the input script (or the current directory when no " "file is specified)." msgstr "輸入腳本所位在的資料夾(如未指定檔案時,則是目前資料夾)。" #: ../../tutorial/modules.rst:196 msgid "" ":envvar:`PYTHONPATH` (a list of directory names, with the same syntax as the " "shell variable :envvar:`PATH`)." msgstr "" ":envvar:`PYTHONPATH`\\ (一連串和 shell 變數 :envvar:`PATH` 的語法相同的資料" "夾名稱)。" #: ../../tutorial/modules.rst:198 msgid "" "The installation-dependent default (by convention including a ``site-" "packages`` directory, handled by the :mod:`site` module)." msgstr "" "與安裝相關的預設值(按慣例會包含一個 ``site-packages`` 資料夾,它是由 :mod:" "`site` 模組所處理)。" #: ../../tutorial/modules.rst:201 msgid "More details are at :ref:`sys-path-init`." msgstr "在 :ref:`sys-path-init` 有更多的細節。" #: ../../tutorial/modules.rst:204 msgid "" "On file systems which support symlinks, the directory containing the input " "script is calculated after the symlink is followed. In other words the " "directory containing the symlink is **not** added to the module search path." msgstr "" "在支援符號連結 (symlink) 的檔案系統中,輸入腳本的所在資料夾是在跟隨符號連結之" "後才被計算的。換言之,包含符號連結的資料夾\\ **並沒有**\\ 增加到模組的搜尋路" "徑中。" #: ../../tutorial/modules.rst:208 msgid "" "After initialization, Python programs can modify :data:`sys.path`. The " "directory containing the script being run is placed at the beginning of the " "search path, ahead of the standard library path. This means that scripts in " "that directory will be loaded instead of modules of the same name in the " "library directory. This is an error unless the replacement is intended. See " "section :ref:`tut-standardmodules` for more information." msgstr "" "初始化之後,Python 程式可以修改 :data:`sys.path`。執行中腳本的所在資料夾會在" "搜尋路徑的開頭,在標準函式庫路徑之前。這代表該資料夾中的腳本會優先被載入,而" "不是函式庫資料夾中相同名稱的模組。除非是有意要做這樣的替換,否則這是一個錯" "誤。 請參見\\ :ref:`tut-standardmodules`\\ 以瞭解更多資訊。" #: ../../tutorial/modules.rst:221 msgid "\"Compiled\" Python files" msgstr "「編譯」Python 檔案" #: ../../tutorial/modules.rst:223 msgid "" "To speed up loading modules, Python caches the compiled version of each " "module in the ``__pycache__`` directory under the name :file:`module." "{version}.pyc`, where the version encodes the format of the compiled file; " "it generally contains the Python version number. For example, in CPython " "release 3.3 the compiled version of spam.py would be cached as ``__pycache__/" "spam.cpython-33.pyc``. This naming convention allows compiled modules from " "different releases and different versions of Python to coexist." msgstr "" "為了加快載入模組的速度,Python 將每個模組的編譯版本暫存在 ``__pycache__`` 資" "料夾下,並命名為 :file:`module.{version}.pyc`, 這裡的 version 是編譯後的檔案" "的格式名稱,且名稱通常會包含 Python 的版本編號。例如,在 CPython 3.3 中," "spam.py 的編譯版本將被暫存為 ``__pycache__/spam.cpython-33.pyc``。此命名準則" "可以讓來自不同版本的編譯模組和 Python 的不同版本同時共存。" #: ../../tutorial/modules.rst:231 msgid "" "Python checks the modification date of the source against the compiled " "version to see if it's out of date and needs to be recompiled. This is a " "completely automatic process. Also, the compiled modules are platform-" "independent, so the same library can be shared among systems with different " "architectures." msgstr "" "Python 根據原始碼最後修改的日期,檢查編譯版本是否過期而需要重新編譯。這是一個" "完全自動的過程。另外,編譯後的模組獨立於平台,因此不同架構的作業系統之間可以" "共用同一函式庫。" #: ../../tutorial/modules.rst:236 msgid "" "Python does not check the cache in two circumstances. First, it always " "recompiles and does not store the result for the module that's loaded " "directly from the command line. Second, it does not check the cache if " "there is no source module. To support a non-source (compiled only) " "distribution, the compiled module must be in the source directory, and there " "must not be a source module." msgstr "" "Python 在兩種情況下不檢查快取 (cache)。首先,它總是重新編譯且不儲存直接從命令" "列載入的模組的結果。第二,如果沒有源模組,則不會檢查快取。要支援非源模組(僅" "編譯)的發布,編譯後的模組必須位於原始資料夾中,並且不能有源模組。" #: ../../tutorial/modules.rst:243 msgid "Some tips for experts:" msgstr "一些給專家的秘訣:" #: ../../tutorial/modules.rst:245 msgid "" "You can use the :option:`-O` or :option:`-OO` switches on the Python command " "to reduce the size of a compiled module. The ``-O`` switch removes assert " "statements, the ``-OO`` switch removes both assert statements and __doc__ " "strings. Since some programs may rely on having these available, you should " "only use this option if you know what you're doing. \"Optimized\" modules " "have an ``opt-`` tag and are usually smaller. Future releases may change " "the effects of optimization." msgstr "" "可以在 Python 指令上使用開關參數 (switch) :option:`-O` 或 :option:`-OO` 來減" "小已編譯模組的大小。開關參數 ``-O`` 刪除 assert(斷言)陳述式,而 ``-OO`` 同" "時刪除 assert 陳述式和 __doc__ 字串。由於有些程式可能依賴於上述這些內容,因此" "只有在你知道自己在做什麼時,才應使用此參數。「已優化」模組有 ``opt-`` 標記," "且通常較小。未來的版本可能會改變優化的效果。" #: ../../tutorial/modules.rst:253 msgid "" "A program doesn't run any faster when it is read from a ``.pyc`` file than " "when it is read from a ``.py`` file; the only thing that's faster about ``." "pyc`` files is the speed with which they are loaded." msgstr "" "讀取 ``.pyc`` 檔案時,程式的執行速度並不會比讀取 ``.py`` 檔案快。唯一比較快的" "地方是載入的速度。" #: ../../tutorial/modules.rst:257 msgid "" "The module :mod:`compileall` can create .pyc files for all modules in a " "directory." msgstr "模組 :mod:`compileall` 可以為資料夾中的所有模組建立 .pyc 檔。" #: ../../tutorial/modules.rst:260 msgid "" "There is more detail on this process, including a flow chart of the " "decisions, in :pep:`3147`." msgstr "更多的細節,包括決策流程圖,請參考\\ :pep:`3147`。" #: ../../tutorial/modules.rst:267 msgid "Standard Modules" msgstr "標準模組" #: ../../tutorial/modules.rst:271 msgid "" "Python comes with a library of standard modules, described in a separate " "document, the Python Library Reference (\"Library Reference\" hereafter). " "Some modules are built into the interpreter; these provide access to " "operations that are not part of the core of the language but are " "nevertheless built in, either for efficiency or to provide access to " "operating system primitives such as system calls. The set of such modules " "is a configuration option which also depends on the underlying platform. " "For example, the :mod:`winreg` module is only provided on Windows systems. " "One particular module deserves some attention: :mod:`sys`, which is built " "into every Python interpreter. The variables ``sys.ps1`` and ``sys.ps2`` " "define the strings used as primary and secondary prompts::" msgstr "" "Python 附帶了一個標準模組庫,詳細的介紹在另一份文件,稱為「Python 函式庫參考" "手冊」(簡稱為「函式庫參考手冊」)。有些模組是直譯器中內建的;它們使一些不屬" "於語言核心但依然內建的運算得以存取,其目的是為了提高效率,或提供作業系統基本" "操作(例如系統呼叫)。這些模組的集合是一個組態選項,它們取決於底層平台。例" "如::mod:`winreg` 模組僅供 Windows 使用。值得注意的模組是 :mod:`sys`,它被內" "建在每個 Python 直譯器中。變數 ``sys.ps1`` 和 ``sys.ps2`` 則用來定義主、次提" "示字元的字串: ::" #: ../../tutorial/modules.rst:283 msgid "" ">>> import sys\n" ">>> sys.ps1\n" "'>>> '\n" ">>> sys.ps2\n" "'... '\n" ">>> sys.ps1 = 'C> '\n" "C> print('Yuck!')\n" "Yuck!\n" "C>" msgstr "" ">>> import sys\n" ">>> sys.ps1\n" "'>>> '\n" ">>> sys.ps2\n" "'... '\n" ">>> sys.ps1 = 'C> '\n" "C> print('Yuck!')\n" "Yuck!\n" "C>" #: ../../tutorial/modules.rst:294 msgid "" "These two variables are only defined if the interpreter is in interactive " "mode." msgstr "只有直譯器在互動模式時,才需要定義這兩個變數。" #: ../../tutorial/modules.rst:296 msgid "" "The variable ``sys.path`` is a list of strings that determines the " "interpreter's search path for modules. It is initialized to a default path " "taken from the environment variable :envvar:`PYTHONPATH`, or from a built-in " "default if :envvar:`PYTHONPATH` is not set. You can modify it using " "standard list operations::" msgstr "" "變數 ``sys.path`` 是一個字串 list,它決定直譯器的模組搜尋路徑。它的初始值為環" "境變數 :envvar:`PYTHONPATH` 中提取的預設路徑,或是當 :envvar:`PYTHONPATH` 未" "設定時,從內建預設值提取。你可以用標準的 list 操作修改該變數: ::" #: ../../tutorial/modules.rst:302 msgid "" ">>> import sys\n" ">>> sys.path.append('/ufs/guido/lib/python')" msgstr "" ">>> import sys\n" ">>> sys.path.append('/ufs/guido/lib/python')" #: ../../tutorial/modules.rst:309 msgid "The :func:`dir` Function" msgstr ":func:`dir` 函式" #: ../../tutorial/modules.rst:311 msgid "" "The built-in function :func:`dir` is used to find out which names a module " "defines. It returns a sorted list of strings::" msgstr "" "內建函式 :func:`dir` 用於找出模組定義的所有名稱。它回傳一個排序後的字串 " "list: ::" #: ../../tutorial/modules.rst:314 msgid "" ">>> import fibo, sys\n" ">>> dir(fibo)\n" "['__name__', 'fib', 'fib2']\n" ">>> dir(sys)\n" "['__breakpointhook__', '__displayhook__', '__doc__', '__excepthook__',\n" " '__interactivehook__', '__loader__', '__name__', '__package__', " "'__spec__',\n" " '__stderr__', '__stdin__', '__stdout__', '__unraisablehook__',\n" " '_clear_type_cache', '_current_frames', '_debugmallocstats', '_framework',\n" " '_getframe', '_git', '_home', '_xoptions', 'abiflags', 'addaudithook',\n" " 'api_version', 'argv', 'audit', 'base_exec_prefix', 'base_prefix',\n" " 'breakpointhook', 'builtin_module_names', 'byteorder', 'call_tracing',\n" " 'callstats', 'copyright', 'displayhook', 'dont_write_bytecode', " "'exc_info',\n" " 'excepthook', 'exec_prefix', 'executable', 'exit', 'flags', 'float_info',\n" " 'float_repr_style', 'get_asyncgen_hooks', " "'get_coroutine_origin_tracking_depth',\n" " 'getallocatedblocks', 'getdefaultencoding', 'getdlopenflags',\n" " 'getfilesystemencodeerrors', 'getfilesystemencoding', 'getprofile',\n" " 'getrecursionlimit', 'getrefcount', 'getsizeof', 'getswitchinterval',\n" " 'gettrace', 'hash_info', 'hexversion', 'implementation', 'int_info',\n" " 'intern', 'is_finalizing', 'last_traceback', 'last_type', 'last_value',\n" " 'maxsize', 'maxunicode', 'meta_path', 'modules', 'path', 'path_hooks',\n" " 'path_importer_cache', 'platform', 'prefix', 'ps1', 'ps2', " "'pycache_prefix',\n" " 'set_asyncgen_hooks', 'set_coroutine_origin_tracking_depth', " "'setdlopenflags',\n" " 'setprofile', 'setrecursionlimit', 'setswitchinterval', 'settrace', " "'stderr',\n" " 'stdin', 'stdout', 'thread_info', 'unraisablehook', 'version', " "'version_info',\n" " 'warnoptions']" msgstr "" ">>> import fibo, sys\n" ">>> dir(fibo)\n" "['__name__', 'fib', 'fib2']\n" ">>> dir(sys)\n" "['__breakpointhook__', '__displayhook__', '__doc__', '__excepthook__',\n" " '__interactivehook__', '__loader__', '__name__', '__package__', " "'__spec__',\n" " '__stderr__', '__stdin__', '__stdout__', '__unraisablehook__',\n" " '_clear_type_cache', '_current_frames', '_debugmallocstats', '_framework',\n" " '_getframe', '_git', '_home', '_xoptions', 'abiflags', 'addaudithook',\n" " 'api_version', 'argv', 'audit', 'base_exec_prefix', 'base_prefix',\n" " 'breakpointhook', 'builtin_module_names', 'byteorder', 'call_tracing',\n" " 'callstats', 'copyright', 'displayhook', 'dont_write_bytecode', " "'exc_info',\n" " 'excepthook', 'exec_prefix', 'executable', 'exit', 'flags', 'float_info',\n" " 'float_repr_style', 'get_asyncgen_hooks', " "'get_coroutine_origin_tracking_depth',\n" " 'getallocatedblocks', 'getdefaultencoding', 'getdlopenflags',\n" " 'getfilesystemencodeerrors', 'getfilesystemencoding', 'getprofile',\n" " 'getrecursionlimit', 'getrefcount', 'getsizeof', 'getswitchinterval',\n" " 'gettrace', 'hash_info', 'hexversion', 'implementation', 'int_info',\n" " 'intern', 'is_finalizing', 'last_traceback', 'last_type', 'last_value',\n" " 'maxsize', 'maxunicode', 'meta_path', 'modules', 'path', 'path_hooks',\n" " 'path_importer_cache', 'platform', 'prefix', 'ps1', 'ps2', " "'pycache_prefix',\n" " 'set_asyncgen_hooks', 'set_coroutine_origin_tracking_depth', " "'setdlopenflags',\n" " 'setprofile', 'setrecursionlimit', 'setswitchinterval', 'settrace', " "'stderr',\n" " 'stdin', 'stdout', 'thread_info', 'unraisablehook', 'version', " "'version_info',\n" " 'warnoptions']" #: ../../tutorial/modules.rst:340 msgid "" "Without arguments, :func:`dir` lists the names you have defined currently::" msgstr "沒有給引數時,:func:`dir` 列出目前已定義的名稱: ::" #: ../../tutorial/modules.rst:342 msgid "" ">>> a = [1, 2, 3, 4, 5]\n" ">>> import fibo\n" ">>> fib = fibo.fib\n" ">>> dir()\n" "['__builtins__', '__name__', 'a', 'fib', 'fibo', 'sys']" msgstr "" ">>> a = [1, 2, 3, 4, 5]\n" ">>> import fibo\n" ">>> fib = fibo.fib\n" ">>> dir()\n" "['__builtins__', '__name__', 'a', 'fib', 'fibo', 'sys']" #: ../../tutorial/modules.rst:348 msgid "" "Note that it lists all types of names: variables, modules, functions, etc." msgstr "請注意,它列出所有類型的名稱:變數、模組、函式等。" #: ../../tutorial/modules.rst:352 msgid "" ":func:`dir` does not list the names of built-in functions and variables. If " "you want a list of those, they are defined in the standard module :mod:" "`builtins`::" msgstr "" ":func:`dir` 不會列出內建函式和變數的名稱。如果你想要列出它們,它們被定義在標" "準模組 :mod:`builtins` 內: ::" #: ../../tutorial/modules.rst:356 msgid "" ">>> import builtins\n" ">>> dir(builtins)\n" "['ArithmeticError', 'AssertionError', 'AttributeError', 'BaseException',\n" " 'BlockingIOError', 'BrokenPipeError', 'BufferError', 'BytesWarning',\n" " 'ChildProcessError', 'ConnectionAbortedError', 'ConnectionError',\n" " 'ConnectionRefusedError', 'ConnectionResetError', 'DeprecationWarning',\n" " 'EOFError', 'Ellipsis', 'EnvironmentError', 'Exception', 'False',\n" " 'FileExistsError', 'FileNotFoundError', 'FloatingPointError',\n" " 'FutureWarning', 'GeneratorExit', 'IOError', 'ImportError',\n" " 'ImportWarning', 'IndentationError', 'IndexError', 'InterruptedError',\n" " 'IsADirectoryError', 'KeyError', 'KeyboardInterrupt', 'LookupError',\n" " 'MemoryError', 'NameError', 'None', 'NotADirectoryError', " "'NotImplemented',\n" " 'NotImplementedError', 'OSError', 'OverflowError',\n" " 'PendingDeprecationWarning', 'PermissionError', 'ProcessLookupError',\n" " 'ReferenceError', 'ResourceWarning', 'RuntimeError', 'RuntimeWarning',\n" " 'StopIteration', 'SyntaxError', 'SyntaxWarning', 'SystemError',\n" " 'SystemExit', 'TabError', 'TimeoutError', 'True', 'TypeError',\n" " 'UnboundLocalError', 'UnicodeDecodeError', 'UnicodeEncodeError',\n" " 'UnicodeError', 'UnicodeTranslateError', 'UnicodeWarning', 'UserWarning',\n" " 'ValueError', 'Warning', 'ZeroDivisionError', '_', '__build_class__',\n" " '__debug__', '__doc__', '__import__', '__name__', '__package__', 'abs',\n" " 'all', 'any', 'ascii', 'bin', 'bool', 'bytearray', 'bytes', 'callable',\n" " 'chr', 'classmethod', 'compile', 'complex', 'copyright', 'credits',\n" " 'delattr', 'dict', 'dir', 'divmod', 'enumerate', 'eval', 'exec', 'exit',\n" " 'filter', 'float', 'format', 'frozenset', 'getattr', 'globals', 'hasattr',\n" " 'hash', 'help', 'hex', 'id', 'input', 'int', 'isinstance', 'issubclass',\n" " 'iter', 'len', 'license', 'list', 'locals', 'map', 'max', 'memoryview',\n" " 'min', 'next', 'object', 'oct', 'open', 'ord', 'pow', 'print', 'property',\n" " 'quit', 'range', 'repr', 'reversed', 'round', 'set', 'setattr', 'slice',\n" " 'sorted', 'staticmethod', 'str', 'sum', 'super', 'tuple', 'type', 'vars',\n" " 'zip']" msgstr "" ">>> import builtins\n" ">>> dir(builtins)\n" "['ArithmeticError', 'AssertionError', 'AttributeError', 'BaseException',\n" " 'BlockingIOError', 'BrokenPipeError', 'BufferError', 'BytesWarning',\n" " 'ChildProcessError', 'ConnectionAbortedError', 'ConnectionError',\n" " 'ConnectionRefusedError', 'ConnectionResetError', 'DeprecationWarning',\n" " 'EOFError', 'Ellipsis', 'EnvironmentError', 'Exception', 'False',\n" " 'FileExistsError', 'FileNotFoundError', 'FloatingPointError',\n" " 'FutureWarning', 'GeneratorExit', 'IOError', 'ImportError',\n" " 'ImportWarning', 'IndentationError', 'IndexError', 'InterruptedError',\n" " 'IsADirectoryError', 'KeyError', 'KeyboardInterrupt', 'LookupError',\n" " 'MemoryError', 'NameError', 'None', 'NotADirectoryError', " "'NotImplemented',\n" " 'NotImplementedError', 'OSError', 'OverflowError',\n" " 'PendingDeprecationWarning', 'PermissionError', 'ProcessLookupError',\n" " 'ReferenceError', 'ResourceWarning', 'RuntimeError', 'RuntimeWarning',\n" " 'StopIteration', 'SyntaxError', 'SyntaxWarning', 'SystemError',\n" " 'SystemExit', 'TabError', 'TimeoutError', 'True', 'TypeError',\n" " 'UnboundLocalError', 'UnicodeDecodeError', 'UnicodeEncodeError',\n" " 'UnicodeError', 'UnicodeTranslateError', 'UnicodeWarning', 'UserWarning',\n" " 'ValueError', 'Warning', 'ZeroDivisionError', '_', '__build_class__',\n" " '__debug__', '__doc__', '__import__', '__name__', '__package__', 'abs',\n" " 'all', 'any', 'ascii', 'bin', 'bool', 'bytearray', 'bytes', 'callable',\n" " 'chr', 'classmethod', 'compile', 'complex', 'copyright', 'credits',\n" " 'delattr', 'dict', 'dir', 'divmod', 'enumerate', 'eval', 'exec', 'exit',\n" " 'filter', 'float', 'format', 'frozenset', 'getattr', 'globals', 'hasattr',\n" " 'hash', 'help', 'hex', 'id', 'input', 'int', 'isinstance', 'issubclass',\n" " 'iter', 'len', 'license', 'list', 'locals', 'map', 'max', 'memoryview',\n" " 'min', 'next', 'object', 'oct', 'open', 'ord', 'pow', 'print', 'property',\n" " 'quit', 'range', 'repr', 'reversed', 'round', 'set', 'setattr', 'slice',\n" " 'sorted', 'staticmethod', 'str', 'sum', 'super', 'tuple', 'type', 'vars',\n" " 'zip']" #: ../../tutorial/modules.rst:391 msgid "Packages" msgstr "套件 (Package)" #: ../../tutorial/modules.rst:393 msgid "" "Packages are a way of structuring Python's module namespace by using " "\"dotted module names\". For example, the module name :mod:`!A.B` " "designates a submodule named ``B`` in a package named ``A``. Just like the " "use of modules saves the authors of different modules from having to worry " "about each other's global variable names, the use of dotted module names " "saves the authors of multi-module packages like NumPy or Pillow from having " "to worry about each other's module names." msgstr "" "套件是一種使用「點分隔模組名稱」組織 Python 模組命名空間的方法。例如,模組名" "稱 :mod:`!A.B` 表示套件 ``A`` 中名為 ``B`` 的子模組。正如模組使用時,不同模組" "的作者不需擔心與其他模組的全域變數名稱重複,點分隔模組名稱的使用,也讓多模組" "套件(像 NumPy 或 Pillow)的作者們不須擔心其他套件的模組名稱。" #: ../../tutorial/modules.rst:401 msgid "" "Suppose you want to design a collection of modules (a \"package\") for the " "uniform handling of sound files and sound data. There are many different " "sound file formats (usually recognized by their extension, for example: :" "file:`.wav`, :file:`.aiff`, :file:`.au`), so you may need to create and " "maintain a growing collection of modules for the conversion between the " "various file formats. There are also many different operations you might " "want to perform on sound data (such as mixing, adding echo, applying an " "equalizer function, creating an artificial stereo effect), so in addition " "you will be writing a never-ending stream of modules to perform these " "operations. Here's a possible structure for your package (expressed in " "terms of a hierarchical filesystem):" msgstr "" "假設你想設計一個能統一處理音訊檔案及音訊數據的模組集(「套件」)。因為音訊檔" "案有很多的不同的格式(通常以它們的副檔名來辨識,例如::file:`.wav`、:file:`." "aiff`、:file:`.au`\\ ),因此,為了不同檔案格式之間的轉換,你會需要建立和維護" "一個不斷增長的模組集合。為了要達成對音訊數據的許多不同作業(例如,音訊混合、" "增加回聲、套用等化器功能、創造人工立體音效),你將編寫一系列無止盡的模組來執" "行這些作業。以下是你的套件可能的架構(以階層式檔案系統的方式表示):" #: ../../tutorial/modules.rst:412 msgid "" "sound/ Top-level package\n" " __init__.py Initialize the sound package\n" " formats/ Subpackage for file format conversions\n" " __init__.py\n" " wavread.py\n" " wavwrite.py\n" " aiffread.py\n" " aiffwrite.py\n" " auread.py\n" " auwrite.py\n" " ...\n" " effects/ Subpackage for sound effects\n" " __init__.py\n" " echo.py\n" " surround.py\n" " reverse.py\n" " ...\n" " filters/ Subpackage for filters\n" " __init__.py\n" " equalizer.py\n" " vocoder.py\n" " karaoke.py\n" " ..." msgstr "" "sound/ Top-level package\n" " __init__.py Initialize the sound package\n" " formats/ Subpackage for file format conversions\n" " __init__.py\n" " wavread.py\n" " wavwrite.py\n" " aiffread.py\n" " aiffwrite.py\n" " auread.py\n" " auwrite.py\n" " ...\n" " effects/ Subpackage for sound effects\n" " __init__.py\n" " echo.py\n" " surround.py\n" " reverse.py\n" " ...\n" " filters/ Subpackage for filters\n" " __init__.py\n" " equalizer.py\n" " vocoder.py\n" " karaoke.py\n" " ..." #: ../../tutorial/modules.rst:438 msgid "" "When importing the package, Python searches through the directories on ``sys." "path`` looking for the package subdirectory." msgstr "Import 套件時,Python 會搜尋 ``sys.path`` 裡的目錄,尋找套件的子目錄。" #: ../../tutorial/modules.rst:441 msgid "" "The :file:`__init__.py` files are required to make Python treat directories " "containing the file as packages (unless using a :term:`namespace package`, a " "relatively advanced feature). This prevents directories with a common name, " "such as ``string``, from unintentionally hiding valid modules that occur " "later on the module search path. In the simplest case, :file:`__init__.py` " "can just be an empty file, but it can also execute initialization code for " "the package or set the ``__all__`` variable, described later." msgstr "" "目錄中必須含有 :file:`__init__.py` 檔案,才會被 Pyhon 當成套件(除非有使用 :" "term:`namespace package`,為一個相對進階的功能);這樣可以避免一些以常用名稱" "命名(例如 ``string``\\ )的目錄,無意中隱藏了較晚出現在模組搜尋路徑中的有效" "模組。在最簡單的情況,:file:`__init__.py` 可以只是一個空白檔案;但它也可以執" "行套件的初始化程式碼,或設置 ``__all__`` 變數,之後會詳述。" #: ../../tutorial/modules.rst:449 msgid "" "Users of the package can import individual modules from the package, for " "example::" msgstr "套件使用者可以從套件中 import 個別模組,例如: ::" #: ../../tutorial/modules.rst:452 msgid "import sound.effects.echo" msgstr "import sound.effects.echo" #: ../../tutorial/modules.rst:454 msgid "" "This loads the submodule :mod:`!sound.effects.echo`. It must be referenced " "with its full name. ::" msgstr "" "這樣就載入了子模組 :mod:`!sound.effects.echo`。引用時必須用它的全名: ::" #: ../../tutorial/modules.rst:457 msgid "sound.effects.echo.echofilter(input, output, delay=0.7, atten=4)" msgstr "sound.effects.echo.echofilter(input, output, delay=0.7, atten=4)" #: ../../tutorial/modules.rst:459 msgid "An alternative way of importing the submodule is::" msgstr "另一種 import 子模組的方法是: ::" #: ../../tutorial/modules.rst:461 msgid "from sound.effects import echo" msgstr "from sound.effects import echo" #: ../../tutorial/modules.rst:463 msgid "" "This also loads the submodule :mod:`!echo`, and makes it available without " "its package prefix, so it can be used as follows::" msgstr "" "這段程式碼一樣可以載入子模組 :mod:`!echo`,並且不加套件前綴也可以使用,因此能" "以如下方式使用: ::" #: ../../tutorial/modules.rst:466 msgid "echo.echofilter(input, output, delay=0.7, atten=4)" msgstr "echo.echofilter(input, output, delay=0.7, atten=4)" #: ../../tutorial/modules.rst:468 msgid "" "Yet another variation is to import the desired function or variable " "directly::" msgstr "另一種變化是直接 import 所需的函式或變數: ::" #: ../../tutorial/modules.rst:470 msgid "from sound.effects.echo import echofilter" msgstr "from sound.effects.echo import echofilter" #: ../../tutorial/modules.rst:472 msgid "" "Again, this loads the submodule :mod:`!echo`, but this makes its function :" "func:`!echofilter` directly available::" msgstr "" "同樣地,這樣也會載入子模組 :mod:`!echo`,但它的函式 :func:`!echofilter` 就可" "以直接使用: ::" #: ../../tutorial/modules.rst:475 msgid "echofilter(input, output, delay=0.7, atten=4)" msgstr "echofilter(input, output, delay=0.7, atten=4)" #: ../../tutorial/modules.rst:477 msgid "" "Note that when using ``from package import item``, the item can be either a " "submodule (or subpackage) of the package, or some other name defined in the " "package, like a function, class or variable. The ``import`` statement first " "tests whether the item is defined in the package; if not, it assumes it is a " "module and attempts to load it. If it fails to find it, an :exc:" "`ImportError` exception is raised." msgstr "" "請注意,使用 ``from package import item`` 時,item 可以是套件的子模組(或子套" "件),也可以是套件中被定義的名稱,像是函式、class (類別)或變數。``import`` " "陳述式首先測試套件中有沒有定義該 item;如果沒有,則會假設它是模組,並嘗試載" "入。如果還是找不到 item,則會引發 :exc:`ImportError` 例外。" #: ../../tutorial/modules.rst:484 msgid "" "Contrarily, when using syntax like ``import item.subitem.subsubitem``, each " "item except for the last must be a package; the last item can be a module or " "a package but can't be a class or function or variable defined in the " "previous item." msgstr "" "相反地,使用 ``import item.subitem.subsubitem`` 語法時,除了最後一項之外,每" "一項都必須是套件;最後一項可以是模組或套件,但不能是前一項中定義的 class、函" "式或變數。" #: ../../tutorial/modules.rst:493 msgid "Importing \\* From a Package" msgstr "從套件中 import \\*" #: ../../tutorial/modules.rst:497 msgid "" "Now what happens when the user writes ``from sound.effects import *``? " "Ideally, one would hope that this somehow goes out to the filesystem, finds " "which submodules are present in the package, and imports them all. This " "could take a long time and importing sub-modules might have unwanted side-" "effects that should only happen when the sub-module is explicitly imported." msgstr "" "當使用者寫下 ``from sound.effects import *`` 時,會發生什麼事?理想情況下,我" "們可能希望程式碼會去檔案系統,尋找套件中存在的子模組,並將它們全部 import。這" "會花費較長的時間,且 import 子模組的過程可能會有不必要的副作用,這些副作用只" "有在明確地 import 子模組時才會發生。" #: ../../tutorial/modules.rst:503 msgid "" "The only solution is for the package author to provide an explicit index of " "the package. The :keyword:`import` statement uses the following convention: " "if a package's :file:`__init__.py` code defines a list named ``__all__``, it " "is taken to be the list of module names that should be imported when ``from " "package import *`` is encountered. It is up to the package author to keep " "this list up-to-date when a new version of the package is released. Package " "authors may also decide not to support it, if they don't see a use for " "importing \\* from their package. For example, the file :file:`sound/" "effects/__init__.py` could contain the following code::" msgstr "" "唯一的解法是由套件作者為套件提供明確的索引。:keyword:`import` 陳述式使用以下" "慣例:如果套件的 :file:`__init__.py` 程式碼有定義一個名為 ``__all__`` 的 " "list,若遇到 ``from package import *`` 的時候,它就會是要被 import 的模組名" "稱。發布套件的新版本時,套件作者可自行決定是否更新此 list。如果套件作者認為沒" "有人會從他的套件中 import \\*,他也可能會決定不支援這個 list。舉例來說,:" "file:`sound/effects/__init__.py` 檔案可包含以下程式碼: ::" #: ../../tutorial/modules.rst:513 msgid "__all__ = [\"echo\", \"surround\", \"reverse\"]" msgstr "__all__ = [\"echo\", \"surround\", \"reverse\"]" #: ../../tutorial/modules.rst:515 msgid "" "This would mean that ``from sound.effects import *`` would import the three " "named submodules of the :mod:`!sound.effects` package." msgstr "" "意思是,``from sound.effects import *`` 將會 import :mod:`!sound.effects` 套" "件中,這三個被提名的子模組。" #: ../../tutorial/modules.rst:518 msgid "" "Be aware that submodules might become shadowed by locally defined names. For " "example, if you added a ``reverse`` function to the :file:`sound/effects/" "__init__.py` file, the ``from sound.effects import *`` would only import the " "two submodules ``echo`` and ``surround``, but *not* the ``reverse`` " "submodule, because it is shadowed by the locally defined ``reverse`` " "function::" msgstr "" "請注意,子模組可能會被區域定義 (locally defined) 的名稱遮蔽。例如,如果你在 :" "file:`sound/effects/__init__.py` 檔案中新增了一個 ``reverse`` 函式,則 " "``from sound.effects import *`` 只會引入兩個子模組 ``echo`` 和 ``surround``," "但\\ *不是* ``reverse`` 子模組,因為它被區域定義的 ``reverse`` 函式遮蔽" "了: ::" #: ../../tutorial/modules.rst:525 msgid "" "__all__ = [\n" " \"echo\", # refers to the 'echo.py' file\n" " \"surround\", # refers to the 'surround.py' file\n" " \"reverse\", # !!! refers to the 'reverse' function now !!!\n" "]\n" "\n" "def reverse(msg: str): # <-- this name shadows the 'reverse.py' submodule\n" " return msg[::-1] # in the case of a 'from sound.effects import *'" msgstr "" "__all__ = [\n" " \"echo\", # 指向 'echo.py' 檔案\n" " \"surround\", # 指向 'surround.py' 檔案\n" " \"reverse\", # !!! 現在指向 'reverse' 函式 !!!\n" "]\n" "\n" "def reverse(msg: str): # <-- 在 'from sound.effects import *' 的情況下\n" " return msg[::-1] # 這個名稱遮蔽了 'reverse.py' 子模組" #: ../../tutorial/modules.rst:534 msgid "" "If ``__all__`` is not defined, the statement ``from sound.effects import *`` " "does *not* import all submodules from the package :mod:`!sound.effects` into " "the current namespace; it only ensures that the package :mod:`!sound." "effects` has been imported (possibly running any initialization code in :" "file:`__init__.py`) and then imports whatever names are defined in the " "package. This includes any names defined (and submodules explicitly loaded) " "by :file:`__init__.py`. It also includes any submodules of the package that " "were explicitly loaded by previous :keyword:`import` statements. Consider " "this code::" msgstr "" "如果 ``__all__`` 沒有被定義,``from sound.effects import *`` 陳述式\\ *並不會" "*\\ 把 :mod:`!sound.effects` 套件中所有子模組都 import 到目前的命名空間;它只" "保證 :mod:`!sound.effects` 套件有被 import(可能會運行 :file:`__init__.py` 中" "的初始化程式碼),然後 import 套件中被定義的全部名稱。這包含 :file:`__init__." "py` 定義(以及被明確載入的子模組)的任何名稱。它也包括任何之前被 :keyword:" "`import` 陳述式明確載入的套件子模組。請看以下程式碼: ::" #: ../../tutorial/modules.rst:543 msgid "" "import sound.effects.echo\n" "import sound.effects.surround\n" "from sound.effects import *" msgstr "" "import sound.effects.echo\n" "import sound.effects.surround\n" "from sound.effects import *" #: ../../tutorial/modules.rst:547 msgid "" "In this example, the :mod:`!echo` and :mod:`!surround` modules are imported " "in the current namespace because they are defined in the :mod:`!sound." "effects` package when the ``from...import`` statement is executed. (This " "also works when ``__all__`` is defined.)" msgstr "" "此例中,當 ``from...import`` 陳述式被執行時,:mod:`!echo` 和 :mod:`!" "surround` 模組被 import 進目前的命名空間,因為它們是在 :mod:`!sound.effects` " "套件裡定義的。(當 ``__all__`` 有被定義時,這規則也有效。)" #: ../../tutorial/modules.rst:552 msgid "" "Although certain modules are designed to export only names that follow " "certain patterns when you use ``import *``, it is still considered bad " "practice in production code." msgstr "" "雖然,有些特定模組的設計,讓你使用 ``import *`` 時,該模組只會輸出遵循特定樣" "式的名稱,但在正式環境 (production) 的程式碼中這仍然被視為是不良習慣。" #: ../../tutorial/modules.rst:556 msgid "" "Remember, there is nothing wrong with using ``from package import " "specific_submodule``! In fact, this is the recommended notation unless the " "importing module needs to use submodules with the same name from different " "packages." msgstr "" "記住,使用 ``from package import specific_submodule`` 不會有任何問題!實際" "上,這是推薦用法,除非 import 的模組需要用到的子模組和其他套件的子模組同名。" #: ../../tutorial/modules.rst:565 msgid "Intra-package References" msgstr "套件內引用" #: ../../tutorial/modules.rst:567 msgid "" "When packages are structured into subpackages (as with the :mod:`!sound` " "package in the example), you can use absolute imports to refer to submodules " "of siblings packages. For example, if the module :mod:`!sound.filters." "vocoder` needs to use the :mod:`!echo` module in the :mod:`!sound.effects` " "package, it can use ``from sound.effects import echo``." msgstr "" "當套件的結構為多個子套件的組合時(如同範例中的 :mod:`!sound` 套件),可以使用" "「絕對 (absolute) import」,引用同層套件中的子模組。例如,要在 :mod:`!sound." "filters.vocoder` 模組中使用 :mod:`!sound.effects` 中的 :mod:`!echo` 模組時," "可以用 ``from sound.effects import echo``。" #: ../../tutorial/modules.rst:573 msgid "" "You can also write relative imports, with the ``from module import name`` " "form of import statement. These imports use leading dots to indicate the " "current and parent packages involved in the relative import. From the :mod:" "`!surround` module for example, you might use::" msgstr "" "你也可以用 ``from module import name`` 的 import 陳述式,編寫「相對 " "(relative) import」。這些 import 使用前導句號指示相對 import 中的目前套件和母" "套件。例如,在 :mod:`!urround` 模組中,你可以使用: ::" #: ../../tutorial/modules.rst:578 msgid "" "from . import echo\n" "from .. import formats\n" "from ..filters import equalizer" msgstr "" "from . import echo\n" "from .. import formats\n" "from ..filters import equalizer" #: ../../tutorial/modules.rst:582 msgid "" "Note that relative imports are based on the name of the current module's " "package. Since the main module does not have a package, modules intended for " "use as the main module of a Python application must always use absolute " "imports." msgstr "" "請注意,相對 import 的運作是以目前模組的套件名稱為依據。因為主模組並沒有套件," "所以如果一個模組預期被用作 Python 應用程式的主模組,那它必須永遠使用絕對引入。" #: ../../tutorial/modules.rst:588 msgid "Packages in Multiple Directories" msgstr "多目錄中的套件" #: ../../tutorial/modules.rst:590 msgid "" "Packages support one more special attribute, :attr:`~module.__path__`. This " "is initialized to be a :term:`sequence` of strings containing the name of " "the directory holding the package's :file:`__init__.py` before the code in " "that file is executed. This variable can be modified; doing so affects " "future searches for modules and subpackages contained in the package." msgstr "" "套件也支援一個特殊屬性 :attr:`~module.__path__`。它在初始化時是一個字串的\\ :" "term:`序列 `\\ 的 :file:`__init__.py` 檔案所在的目錄名稱,初始化時" "機是在這個檔案的程式碼被執行之前。這個變數可以被修改,但這樣做會影響將來對套" "件內的模組和子套件的搜尋。" #: ../../tutorial/modules.rst:597 msgid "" "While this feature is not often needed, it can be used to extend the set of " "modules found in a package." msgstr "雖然這個特色不太常被需要,但它可用於擴充套件中的模組集合。" #: ../../tutorial/modules.rst:602 msgid "Footnotes" msgstr "註解" #: ../../tutorial/modules.rst:603 msgid "" "In fact function definitions are also 'statements' that are 'executed'; the " "execution of a module-level function definition adds the function name to " "the module's global namespace." msgstr "" "實際上,函式定義也是「被執行」的「陳述式」;在執行模組階層的函式定義時,會將" "函式名稱加到模組的全域命名空間。" #: ../../tutorial/modules.rst:186 ../../tutorial/modules.rst:269 #: ../../tutorial/modules.rst:350 msgid "module" msgstr "module(模組)" #: ../../tutorial/modules.rst:186 msgid "search" msgstr "search(搜尋)" #: ../../tutorial/modules.rst:186 msgid "path" msgstr "path(路徑)" #: ../../tutorial/modules.rst:269 msgid "sys" msgstr "sys" #: ../../tutorial/modules.rst:350 msgid "builtins" msgstr "builtins(內建)" #: ../../tutorial/modules.rst:495 msgid "__all__" msgstr "__all__"