首頁 >後端開發 >Python教學 >Python 2.7基礎教學之:模組

Python 2.7基礎教學之:模組

黄舟
黄舟原創
2016-12-24 17:10:371588瀏覽

.. _tut-modules:

************************

Modules 模組

*********** *************

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。 , 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

handy function that you've written in several programs out Python 解譯器重新進入,先前建立的一切定義(變數和函數)就全

部遺失了。因此,如果你想寫一些長久保存的程序,最好使用一個文字編輯器來

編寫程序,把保存好的文件輸入解釋器。我們稱之為創建一個 *腳本* 。或者程

序變得更長了,你可能為了方便維護而把它分開成幾個文件。你也可能想要在幾

個程式中都使用一個常用的函數,但是不想把它的定義複製到每一個程式裡。

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

* a can a​​n背* 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).提供了一個方法可以從檔案中取得定義,在腳本或

解釋器的一個互動實例中使用。這樣的檔案稱為*模組* ;模組中的定義可

以*導入* 

到另一個模組或主模組中(在腳本執行時可以調用的變數集位於最高級,並且處

於計算器模式)。

A module is a file containing Python definitions and statements.  The file name

is the module name with the suffix :file:`.py` appended。 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是包含Python 定義和聲明的檔案。檔案名稱就是模組名稱加上 :file:`.py` 字尾。模

區塊的模組名(做為一個字串)可以由全域變數 ``__name__`` 得到。例如,你可以

用自己慣用的文件編輯器在當前目錄下創建一個叫:file:`fibo.py` 的文件,錄入如下

內容::

   # Fibonacci numbers module

   def fib(n ):    # write Fibonacci series up to n

       a, b = 0, 1

       while b    def fib2(n): # return Fibonacci series up to n

       result = []

       a, b = 0, 1

       a, b = 0, 1

       a, b = 0, 1

   )  

           a, b = b, a+b

       return result

Now enter the Python interpreter and import this module with the following

command:

現在進入Python解釋器,用以下指令導入這個模組::

noto> notimport bo nothih ? of the functions defined in ``fibo``  directly in

the current symbol table; it only enters the module name ``fibo`` there. Using

the module name unccan `` there. Using acc

the module name unction modess` there. Usingsacc直接把``fibo`` 中的函數導入目前的語意表;它只是引入了模組名

``fibo`` 。你可以透過模組名稱如下存取這個函數::

   >>> fibo.fib(1000)

   1 1 2 3 5 8 13 21 34 55 89 144 233 5 8 13 21 34 55 89 144 233377 61 (100)

   [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]

   >>> fibo.__name__

  often you can assign it to a local name:

如果你想要直接呼叫函數,通常可以給它一個本地名稱::

   >>> fib = fibo.fib

   >>> fib(500)

  

   1 1 2 3 5 8 13 21 34 55 89 144 233 377

.. _tut-moremodules:

More on Modules 深入模組

==============================

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 is imported somewhere. [#]_

模組可以像函數定義一樣包含執行語句。這些語句通常用於初始化模組。它們只

在模組 *第一次* 導入時執行一次。 [#]_

Each module 有 its own private symbol table, which is used as the global symbol

table by all functions defined in the module. Thus, the horhorhoro soo​​an can卷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 uncule's gfer in vables with the samek you can touch a uncule's gferari s`ables with the same ``us . itemname``.

對應於定義模組中所有函數的全域語意表,每個模組都有自己的私有語意表。因

此,模組作者可以在模組中使用一些全域變量,不會因為與使用者的全域變數衝突

而引發錯誤。另一方面,如果你確定你需要這個,可以像引用模組中的函數一樣取得模組中的全域變量,形如: ``modname.itemname`` 。

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 word:`import` statements at the beginning of a module (or script, for word:`import` statements at the beginning of a module (or script, for thatmplace name thatm. the importing module's global

symbol table.

模組可以導入( :keyword:`import` )其它模組。習慣上所有的 import 語句都放在模組(或

腳本,等等)的開頭,但這並不是必須的。被導入的模組名入在本模組的全域語

義表中。

There is a variant of the :keyword:`import` statement that imports names from a

module directly into the importing module's symbol table. 語句接句 example:``imumle:`words 773:203:`ample:`words `ample:`word導入的模組中導入命名到本模組的語意表中。

例如::

   >>> from fibo import fib, fib2

   >>> fib(500)

   1 1 2 3 5 8 13 21    1 1 2 3 5 8 13 21 3434373453567435 367453 373567 3437 3437 34375 3437 34373567 34367233 337235366 not introduce the module name from which the imports are taken in the

local symbol table (so in the example, ``fibo`` is not defined).

這樣不會從局域語意表中導入模組名(如上圖所示, `` fibo`` 沒有定義)。

There is even a variant to import all names that a module defines:

甚至有種方式可以導入模組中的所有定義::

   >>> from fibo import *

   >>> from fibo import *

>

   1 1 2 3 5 8 13 21 34 55 89 144 233 377

This imports all names except those beginning with an underscore (``_``(````) 或是所有這些劃線 ``score (``_````)。 )開頭的命名。

Note that in general the practice of importing ``*`` from a module or package is

frowned upon, since it often causes poorly readable code. However, intertoions toever🜟 interto interlever, intertoions tos intereveral intertoal interFs interFs interoreals intert 2575, intert. .

需要注意的是在實踐中往往不鼓勵從一個模組或包中使用``*`` 導入所有,因

為這樣會讓代碼變得很難讀。不過,在互動式會話中這樣用很方便省力。

.. note::

.. [#] For efficiency reasons, each module is only imported once per interpreter

   session. if it's just one module you want to test interactively,

   use :func:`reload`, e.g. ``reload(modulename)``.

.. [#] 性能考慮,每個模組在每個解釋器會話中只導入一遍。因此,如果你修

   改變了你的模組,需要重啟解釋器——或者,如果你就是想交互式的測試這麼一

   個模組,可以用:func:`reload` 重新加載,例如`` reload(modulename)`` 。

.. _tut-modulesasscripts:

Executing modules as scripts 作為腳本來執行模組

----------------------------- ---------------------

When you run a Python module with :

使用以下方式執行一個Python 模組::

   python fibo.py

the code in the module will be executed, just as if you imported it, but with

the ``__name__`` set to ``"__main__"``.  That means that end of your module:

模組中的程式碼會被執行,就像導入它一樣,不過此時``__name__`` 被設定為

``"__main__"`` 。這相當於,如果你在模組後加入以下程式碼 ::

   if __name__ == "__main__":

       import sys

       fib(int(sys.argv[1]))

you can make the file usable as a script as as

you can make the file usable as a script as as

youable asrun the filesable as a script as as as

if the module is

executed as the "main" file:

就可以讓此檔案像作為模組導入時一樣作為腳本執行。此程式碼只有在模組作為

「main」 檔案執行時才被呼叫::

   $ python fibo.py 50

   1 1 2 3 5 8 13 21 34

run:

如果模組被導入,不會執行這段程式碼::

   >>> import fibo

   >>>

This is often used either to provide a conven ​​動user inter toface 詞testing purposes (running the module as a script executes a test suite).

這通常用來為模組提供一個便於測試的使用者介面(將模組作為腳本執行測試需求)。

.. _tut-searchpath:

The Module Search Path 模組搜尋路徑

------------------------------- --------------

.. index:: triple: module; search; path

When a module named :mod:`spam` is imported, the interpreter searches for a file

named :file:`spam.py` in the current directory, and then in the list of

directories specified by the environment variable :envvar:`PYTHONPATH`.  This s `PATH`, that is, a list of

directory names.  When :envvar:`PYTHONPATH` is not set, or when the file is not

found there, the search continues in an not

found there, the search continues in an 反對詞

Unix, this is usually :file:`.:/usr/local/lib/python`.

導入一個叫:mod:`spam` 的模組時,解釋器先在目前目錄中搜尋名為

: file:`spam.py` 的文件,然後在環境變數:envvar:`PYTHONPATH` 表示的目錄

列表中搜索,然後是環境變數:envvar:`PATH` 中的路徑列表。如果

:envvar:`PYTHONPATH` 沒有設置,或者檔案沒有找到,接下來搜尋安裝目錄,

在 Unix 中,通常是 :file:`.:/usr/local/lib/python` 。

Actually, modules are searched in the list of directories given by the variable

``sys.path`` which is initialized from the directory containing the input script

(or the current from the directory containing the input script

(or the current): and the installation- dependent

default.  This allows Python 內容is important that the script not have

the same name as a standard module, or Python will attempt to load the script as

a module when that module is imported. This will generally be Hh. `tut-standardmodules` for more information.

實際上,解釋器由``sys.path`` 變數指定的路徑目錄搜尋模組,該變數初始化

時預設包含了輸入腳本(或目前目錄), : envvar:`PYTHONPATH` 和安裝目錄。

這樣就允許 Python 程式了解如何修改或取代模組搜尋目錄。要注意的是由於

這些目錄中包含有搜尋路徑中運行的腳本,所以這些腳本不應該和標準模組重

名,否則在導入模組時 Python 會嘗試把這些腳本當作模組來載入。這通常會引

發錯誤。請參閱 :ref:`tut-standardmodules` 以了解更多的資訊。

"Compiled" Python files 「編譯的」 Python 檔案

----------------------------------- -------------------

As an important speed-up of the start-up time for short programs that use a lot

of standard modules, if a file called :file:`spam.pyc` exists in the directory

where :file:`spam.py` is found, this is assumed to contain an

`. The modification time

of the version of :file:`spam.py` used to create :file:`spam.pyc` is recorded in

:file:`spam.pyc`, and the :file:` .pyc` file is ignored if these don't match.

對於引用了大量標準模組的短程序,有一個提高啟動速度的重要方法,如果在

:file:`spam.py` 所在的目錄下存在一個名為:file:`spam.pyc` 的文件,它會

被視為:mod:`spam` 模組的預「編譯」(``byte-compiled'' ,二進位編譯)

版本。用於建立:file:`spam.pyc` 的這一版:file:`spam.py` 的修改時間記

錄在:file:`spam.pyc` 檔案中,如果兩者不匹配,:file :`.pyc` 檔案就被忽

略。

Normally, you don't need to do anything to create the :file:`spam.pyc` file.

Whenever :file:`spam.py` is successfully compiled, an attemptrite is made to write

the compiled version to :file:`spam.pyc`.  It is not an error if this attempt

fails; if for any reason the file is not written completely, the resulting `hm`. will be recognized as invalid and thus ignored later.  The

contents of the :file:`spam.pyc` file are platform independent, so a Python

module ditory can be sharedby需要為建立:file:`spam.pyc` 檔案做任何工作。一旦 :file:`spam.py` 成功編譯,就

會嘗試產生對應版本的 :file:`spam.pyc` 。如果有任何原因導致寫入不成功,

產生的 :file:`spam.pyc` 檔案就會被視為無效,隨後即被忽略。 :file:`spam.pyc` 檔案的內容是平台獨

立的,所以Python模組目錄可以在不同架構的機器之間共用。

Some tips for experts:

部分進階技巧:

* When the Python interpreter is invoked with the :option:`-O` flag, optimized

🜥 集帶 集......p. .  The optimizer currently

  doesn't help much; it only removes :keyword:`assert` statements。 .pyc`` files are

  ignored and ``.py`` files are compiled to optimized bytecode.

  以file:option:`-O` 參數呼叫Python解釋器時,會產生程式碼並儲存碼`.pyo` 文件中。現

  在的最佳化器沒有太多幫助;它只是刪除了斷言( :keyword:`assert` )語句。使用:option:`-O` 參

  參數, *所有* 的字節碼( :term:`bytecode` )都會被最佳化; ``.pyc`` 文字

  件被忽略, ``.py` ` 檔案被編譯為最佳化程式碼。

* Passing two :option:`-O` flags to the Python interpreter (:option:`-OO`) will

  cause the bytecode compiler to perform optimizations that cem in somes mal in集🠎ion uncet only ``__doc__`` strings are

  removed from the bytecode, resulting in more compact :file:`.pyo` files.  Since

. if you know what you're doing.

  傳遞兩個:option:`-O` 參數( :option:`-OO` )會執行完全

  優化的二進位最佳化,這偶爾會產生錯誤的程式.現在的最佳化器,只是從字

  節碼中刪除了 ``__doc__`` 符串,產生更為緊湊的 :file:`.pyo` 檔案。因為

  某些程式依賴這些變數的可用性,你應該只在確定無誤的場合使用這個選項。

* A program doesn't run any faster when it is read from a :file:`.pyc` or

  :file:`.pyo` file than when it is read from a :file:`.py` filefile:`.py` filefile:`.py` filefile:`.py` filefile:`.py` filefile:`. ; the only thing

  that's faster about :file:`.pyc` or :file:`.pyo` files is the speed with which

  they are loaded.

:`py:``file :`.pyo` 檔案中的程式不會比來自

  :file:`.py` 檔案的運作更快; :file:`.pyc` 或:file:`.pyo` 檔案只是在

  它們載入的時候更快一些。

* When a script is run by giving its name on the command line, the bytecode for

  the script is never written to a :file:`.pyc` or ::`.pyo file:`.pyo

  startup time of a script may be reduced by moving most of its code to a module

  and having a small bootstrap. :`.pyo` file directly on the command

  line.

  在命令列中執行腳本時,並不會將為此腳本建立的二進位程式碼寫入

 :`.pyo` 文件。當然,把腳本的主要程式碼移進一個模

  塊裡,然後用一個小的啟動腳本導入這個模組,就可以提高腳本的啟動速度。

  也可以直接在命令列中指定一個 :file:`.pyc` 或 :file:`.pyo` 檔案。

* It is possible to have a file called :file:`spam.pyc` (or :file:`spam.pyo`

  when :option:`-O` is used) without a filefile:`spam .py` for the same module.

  This can be used to distribute a library of Python code in a form that is

  moderately hard to reverse engineer.

  moderately hard to reverse engineer。 .py` --譯者),可以只

  有:file:`spam.pyc` 檔案(或:file:`spam.pyc` ,在使用

  :option:`-O` 參數時)而沒有:file:`spam.py` 檔案。這樣可以打包發布比

  較難於逆向工程的 Python 程式碼庫。

  .. index:: module: compileall

* The module :mod:`compileall` can create :file:`.pyc` files (or :file:`.pyo`

` is used) for all modules in a directory.

  :mod:`compileall` 模組可以為指定目錄中的所有模組建立:file:`.pyc` 文字

  件(或使用:file:`.pyc`file:`.pyo`file:`.pyo`file:`.pyo`file:`.pyo參數建立:file:`.pyo` 檔案)。

.. _tut-standardmodules:

Standard Modules 標準模組

================================

.. index:: module: sys

Python comes with a library of standard modules, described in a separate

document, the Python Library Reference ("Library Reference" hereafter)。 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 athtention: ​​ihei​​dicular module: some at`h. every Python interpreter.  The variables

``sys.ps1`` and ``sys.ps2`` define the strings used as primary and secondary

prompts:

Python

Pyt文檔,名為Python 庫參考手冊

(此後稱為「庫參考手冊」)。有一些模組內建在解釋器之中,這些操作的訪

問介面不是語言核心的一部分,但是已經內建在解釋器中了。這既是為了提高效

率,也是為了給系統呼叫等作業系統原生存取提供介面。這類模組集合是依

賴於底層平台的設定選項。例如,:mod:`winreg` 模組只提供在 Windows 系統

上才有。有一個具體的模組值得注意: :mod:`sys` ,這個模組內建於所有的

Python 解釋器。變數sys.ps1 和sys.ps2定義了主提示符號和副助提示符號字串::

   >>> import sys

   >>> sys.ps1

   '>>> '

> .ps2

   '... '

   >>> sys.ps1 = 'C> '

   C> print 'Yuck!'

   Yuck!bpedhio🜥 internable intermedo​​hhk生活ter is in interactive mode.

這兩個變數只在解釋器的交互模式下有意義。

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

es. It is initialized to a default path taken from the

機。 a built-in default if

:envvar:`PYTHONPATH` is not set.  You can modify it using standard list

operations:

變數``sys.path`` 是解釋字串列表器模組的字串列表器。它由環境變

量:envvar:`PYTHONPATH` 初始化,如果沒有設定 :envvar:`PYTHONPATH` ,就由

內建的預設值初始化。你可以用標準的字串操作修改它::

   >>> import sys

   >>> sys.path.append('/ufs/guido/lib/python')

.. _tut-dir:

The :func:`dir` Function :func:`dir` 函數

================================ ======================

The built-in function :func:`dir` is used to find out which names a module

defines.  It returns a sorted list of strings:

內建函數:func:`dir` 用於依模組名搜尋模組定義,它傳回一個字串型別的儲存列

表::

   >>> import fibo, sys

  >>> dir(fibo)

   ['__name__', 'fib', 'fib2']

   >>> dir(sys)

   ['__displayhook__', '__doc__

   ['_____displayhook__', '__doc__

   ['__displayhook__', '__doc__', 'ex__k__k__', 'ex__k__ob__', 'ex__k__', '0. '__stderr__',

    '__stdin__', '__stdout__', '_getframe', 'api_version', 'argv',

    'builtin_module_names',

    'builtin_module_names',

     ' ', 'exc_clear', 'exc_info', 'exc_type', 'excepthook',

    'exec_prefix', 'executable', 'exit', 'getdefaultencoding', 'getdlopflags',🠎ion' ', 'maxint', 'maxunicode',

    'meta_path', 'modules', 'path', 'path_hooks', 'path_importer_cache',

    'platform', 'prefix', 'ps1', 'openps2', 'setcheckvallag) setprofile', 'setrecursionlimit', 'settrace', 'stderr', 'stdin', 'stdout',

    'version', 'version_info', 'warnoptions']

Without arguments, :func`list:func `list names you have defined currently:

無參數呼叫時, :func:`dir` 函數傳回目前定義的命名::

   >>> a = [1, 2, 3, 4, 5]

>> > import fibo

   >>> fib = fibo.fib

   >>> dir()

   ['__builtins__', '__docbo', '__file__', '__name__', 'a, 'fi 'fib' , 'sys']

Note that it lists all types of names: variables, modules, functions, etc.

注意該列表列出了所有類型的名稱:變量,模組,函數,等等。

.. index:: module: __builtin__

:func:`dir` does not list the names of built-in functions and variables.  If you

A list of le :mod:`__builtin__`:

:func:`dir` 不會列出內建函數和變數名稱。如果你想列出這些內容,它們在標準模組

:mod:`__builtin__` 中定義::

   >>> import __builtin__

   >>> dir(__builtin__)rr

   >>> dir(__builtin__)rr

  > dir(__builtin__)rr

'Errorh [prror [roror; , 'AttributeError', 'DeprecationWarning',

    'EOFError', 'Ellipsis', 'EnvironmentError', 'Exception', 'False',

,’Error', 'Exception', 'False',

收到, 'OSError', ' OverflowError',

    'PendingDeprecationWarning', 'ReferenceError', 'RuntimeError',

    'Run​​StandardWarning', 'Error', 'StopIteration, 'on'oin' ', 'SystemError', 'SystemExit', ' TabError', 'True',

    'TypeError', 'UnboundLocalError', 'UnicodeDecodeError',

    'UniEncodeError', 'UniUniError或', 'Warning', ' WindowsError',

    'ZeroDivisionError', '_', '__debug__', '__doc__', '__import__',

    '__name__', 'abs', 'apply', 'string' ,

    'callable', 'chr', 'classmethod', 'cmp', 'coerce', 'compile',

    'complex', 'copyright', 'credits', 'delattr', 'dict' dir', 'divmod',

    'enumerate', 'eval', 'execfile', 'exit', 'file', 'filter', 'float',

    'frozenset', 'float',

    'frozenset', 'float', 'globals' , 'hasattr', 'hash', 'help', 'hex',

    'id', 'input', 'int', 'intern', 'isinstance', 'issubclass', 'iter',

    len', 'license', 'list', 'locals', 'long', 'map', 'max', 'memoryview',

    'min', 'object', 'oct', 'open', ' ord', 'pow', 'property', 'quit', 'range',

    'raw_input', 'reduce', 'reload', 'repr', 'reversed', 'round', 'set',

    'setattr', 'slice', 'sorted', 'staticmethod', 'str', 'sum', 'super',

    'tuple', 'type', 'unichr', 'unicode', 'vars' , 'xrange', 'zip']

.. _tut-packages:

Packages 包

==============

Packages are a way of structuring Python's module namespace by using "dotted

module names".  For example, the module name

module names"。 submodule

named ``B`` in a package named ``A``.  Just like the use of modules saves the

authors of different modules from having to orry module names saves the authors of multi-module

packages like NumPy or the Python Imaging Library from having to worry about

each other's module names.

包裝。例如,名為

:mod:`A.B` 的模組表示了名為 ``B`` 的套件中名為 ``A`` 的子模組。正如同用

模組來保存不同的模組架構可以避免全局變數之間的相互衝突,使用圓點模組名

保存像NumPy 或Python Imaging Library 之類的不同類庫架構可以避免模組

之間的命名衝突。

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 files and sound data。 file:`.wav`,

:file:`.aiff`, :file:`.au`), so you may need to create and maintain a growing

collection of modules for the conversion between the var

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 mixing, adding echo, applying an equalizer function, creating mixing, adding echo, applying an equalizer function, creating commage comhed 3hed 3hed 3050000y yage woo​​l creating commper perialrbe unperk有k-wunk-wun​​hkh unperkathun​​lkh un​​hly ungey ungeat unwy-ununyh ungeat ungeat 片面ending

stream of modules to perform these operations.  Here's a possible structure for

your package (expressed in terms of a hierarchical filesystem):

假設你現在想要一個套件集(統一包聲音檔案和聲音資料。

存在著幾種不同的聲音格式(通常由它們的副檔名來標識,例如: :file:`.wav`

, :file:`.aiff` , :file:`.au` ),於是,為了在不同類型的檔案格式之間

轉換,你需要維護一個不斷增長的套件集合。也許你還想要對聲音數據做很多不同

的操作(例如混音,添加迴聲,應用平衡功能,創建一個人造效果),所以你要

加入一個無限流模組來執行這些操作。你的包包可能會是這個樣子(透過分級的文字

件系統來進行分組) ::

   sound/                                 Initialize the sound package

         formats/                 

                 __init__.py

                 wavread.py

                 wavwrite.py

                 aiffread.py

                 aiffwrite.py

                 auread.py

                 auwrite.py

                 ...

         effects/                  Subpackage for sound effects

                 __init__ .py

                 echo.py

                 surround.py

                 reverse.py

                 ...

         filters/                  Subpackage for filters

                 __init__.py

                 equalizer.py

                 vocoder.py

                 karaoke.py

                 ...

When importing the package, Python searches through the directories on

``sys.path`` looking for the directories on

``sys.path`` looking for the directories on

``sys.path`` looking for the package subdiing列表來搜尋存放包的子目錄。

The :file:`__init__.py` files are required to make Python treat the directories

as containing packages; `__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. .py` 檔案的存在,才能使Python 視該目錄為

一個套件;這是為了防止某些目錄使用了``string`` 這樣的通用名稱而無意中在隨

後的模組搜尋路徑中覆蓋了正確的模組。最簡單的情況下,

:file:`__init__.py` 可以只是一個空文件,不過它也可能包含了包的初始化代碼,或者設置了 ``__all__`` 變量,後面會有相關介紹。

Users of the package can import individual modules from the package, for

example:

包用戶可以從包中導入合法的模組,例如::

. mod:`sound.effects.echo`.  It must be referenced with

its full name. :

這樣就導入了:mod:`Sound.Effects.echo` 子模組。它必需透過完整的名稱來引用。 ::

   sound.effects.echo.echofilter(input, output, delay=0.7, atten=4)

An alternative way of importing the submodule is:::

An alternative way of importing the submodule is:::

An alternative way of importing the submodule is:::

An alternative way of importing the submodule is: from sound.effects import echo

This also loads the submodule :mod:`echo`, and makes it available without its

package prefix, so it can be used as follows:choas follows: 就這樣載入了` 子模組,並且使得它在沒有包前綴的情況下也可以

使用,所以它可以如下方式調用::

   echo.echofilter(input, output, delay=0.7, atten=4)

Yet an variation is to import the desired function or variable directly:

還有另一種變體用於直接導入函數或變數::

   from sound.effects.echo import echofilter

A this loads themod this: loads the subule: loads thesubule: loads the subule: loads thesubule: loads the subule: loads thesubule: loads the subule: loads thesubule: loads thesubpule: loads thesubpule: loads thesubule: loads thesubpule: loads thesubpule: loads thesubule: loads the subule: loads thesubpule: loads thesubule: loads thesubpule: loads thesubpule: loads thesubpule: loads thesubpule: loads thesubule: loads thesubule: loads thesubpule load `echo`, but this makes its function

:func:`echofilter` directly available:

這樣就又一次載入了:mod:`echo` 子模組,但這樣就可以直接呼叫它的

:func: `echofilter` 函數::

   echofilter(input, output, delay=0.7, atten=4)

Note that when using ``from package import item``, the item can be either 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 isage; a

module and attempts to load it.  If it fails to find it, an :exc:`ImportError`

exception is raised.

需要注意的是使用``fromitage is raised。這個子項(item)既可以是包中的一個子模組(或一個子包),也可以是包中定義的其它命名,像函數、類別或變數。 import 語句首先核對是否套件中有這個子項,如果沒有,它假定這是一個模組,並嘗試載入它。如果沒有找到它,會引發一個 ImportError 異常。

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 abe class or function or variable defined in the previous

item.

相反,使用類似``import item.subitem.subsubitem`` 這樣的語法時,這些子項必

須是包,最後的子項可以是包,最後的子項可以是套件或模組,但不能是前面子項定義的類別、函數或變

量。

.. _tut-pkg-import-star:

Importing /* From a Package

---------------------------

。 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 haveen sub片寫下``from sound.Effects import *`` 時會發生什麼事?理想中,總

是希望在檔案系統中找出套件中所有的子模組,然後導入它們。這可能會花掉委有

長時間,並且出現期待之外的邊界效應,導出了希望只能明確導入的包。

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`py: ) list named ``__all__``, it is taken to be the

list of module names that should be imported when ``from package import *`` is

encountered。 use for importing /* from their package.  For

example, the file :file:`sounds/effects/__init__.py` could contain the following

code:

could contain the following

code:

對於包的作者來說是唯一的解決方案提供一個明確的包索引。

:keyword:`import` 語句按如下條件進行轉換:執行``from package import

*`` 時,如果套件中的:file:`__init__.py` 程式碼定義了一個名為``__all__` `

的列表,就會依照列表中給出的模組名來導入。新版的包裝發佈時作者可以任

意更新這個清單。如果套件作者不想 import * 的時候導入他們的套件中所有模組,

那麼也可能會決定不支援它(import /*)。例如,

:file:`Sounds/Effects/__init__.py` 這個檔案可能包含以下程式碼::

   __all__ = ["echo", "surround", "reverse"]

This would mean that ``from sound.effects import *`` would import the three

named submodules of the :mod:`sound` package.

這表示``from Sound.Effects import *`` 語句會從:mod:`sound` 包中導入以上三個已命名的子模組。

If ``__all__`` is not defined, the statement ``from sound.effects import *``

does *not* import all submodules from the package :mod:`sound. ; it only ensures that the package :mod:`sound.effects` has

been imported (possibly running any initialization code in :file:`__init__.py`)

and then ports areheverone the careed includes any

names defined (and submodules explicitly loaded) by :file:`__init__.py`.  It

also includes any submodules of the substate that were ider this code:

如果沒有定義``__all__`` , ``from Sound.Effects import *`` 語句不會從

:mod:`sound.effects` 套件中導入所有的子模組。無論套件中定義多少命名,只能

確定的是導入了:mod:`sound.effects` 包(可能會運行__init__.py 中的初

始化代碼)以及包中定義的所有命名會隨之導入。這樣就從 ``__init__.py``

中導入了每一個命名(以及明確導入的子模組)。同樣也包含了前述的

:keyword:`import` 語句從包中明確導入的子模組,考慮以下程式碼::

   import sound.effects.echo

   import sound.effect.surround

   import sound. effects import *

In this example, the :mod:`echo` and :mod:`surround` modules are imported in the

current namespace because they are defined in the :

current namespace because they are defined in the :3:`f . the ``from...import`` statement is executed.  (This also works when

``__all__`` is defined.)

在這個例子中, :mod:`echo` 和:mod:`surround`模組導入了目前的命名空

間,這是因為執行``from...import`` 語句時它們已經定義在

:mod:`sound.effects` 套件中了(定義了``__all__` ` 時也會同樣工作)。

Although certain modules are designed to export only names that follow certain

patterns when you use ``import *``, it is still considered bad practise in``import *``, it is still considered bad practise in`imimport *``, s. import *`` 時它只導出符全某種模式的命名,仍然

不建議在生產代碼中使用這種寫法。

Remember, there is nothing wrong with using ``from Package import

specific_submodule``!  In fact, this is the recommended notation unless the💎 s.

記住, ``from Package import specific_submodule`` 沒有錯誤!事實上,除

非導入的模組需要使用其它包中的同名子模組,否則這是建議的寫法。

Intra-package References 包內引用

-------------------------------------

The submodules often need to refer to each other.  For example, the

:mod:`surround` module might use the :mod:`echo` module.  In fact, such

reference soare import` statement first looks in the

containing package before looking in the standard module search path. Thus, the

:mod:`surround` module can simply use ``import echo`` or ``from echo import

echofilter ``.  If the imported module is not found in the current package (the

package of which the current module is a submodule), the :keyword:`import`

statement looks for top-leven .

子模組之間經常需要互相引用。例如,:mod:`surround` 模組可能會引用

:mod:`echo` 模組。事實上,這樣的引用如此普遍,以致於 :keyword:`import`

語句會先搜尋套件內部,然後才是標準模組搜尋路徑。因此 :mod:`surround` 模

塊可以簡單的調用 ``import echo`` 或 ``from echo import echofilter``

。如果沒有在目前的套件中發現要導入的模組,:keyword:`import` 語句會依據指

定名尋找一個頂層模組。

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 socp `sound.filters.vocoder` needs to use

the :mod:`echo` module in the :mod:`sound.effects` package, it can use ``from

sound.effects import echo`.

.如果套件中使用了子包結構(就像範例中的:mod:`sound` 套件),可以按絕對位置

從相鄰的套件中引入子模組。例如,如果:mod:`sound.filters.vocoder` 套件需要

使用:mod:`sound.effects` 套件中的:mod:`echo` 模組,它可以

``from Sound.Effects import echo` ` 。

Starting with Python 2.5, in addition to the implicit relative imports described

above, you can write explicit relative imports with the ``from module import

紙 name imports nameimport ​​外表帶 含義 含義

表 假面 String`​​l.

dots to indicate the current and parent packages involved in the relative

import. From the :mod:`surround` module for example, you might use:

從Python 2.5 開始,前述的位置相對導入得到改進,你可以用這樣

的形式``from module import name`` 來寫明確的相對位置導入。那些顯式相

對導入用點號標明關聯導入當前和上級包。以:mod:`surround` 模組為例,你可以

這樣用::

   from . import echo

   from .. import formats

are based on the name of

the current module. Since the name of the main module is always ``"__main__"``,

modules intended for use as the main useule of a .

需要注意的是顯式或隱式相對位置導入都基於當前模組的命名。因為主模組的名稱

字總是 ``"__main__"`` ,Python 應用程式的主模組應該總是用絕對導入。

Packages in Multiple Directories 多重目錄中的套件

------------------------------------- -----------------

Packages support one more special attribute, :attr:`__path__`.  This is

initialized to be a list 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 packone and modified;為特殊的特性, :attr:`__path__` 。 在套件的

:file:`__init__.py` 

檔案程式碼執行之前,該變數會初始化一個目錄名稱清單。該變數可以修改,它作用於

套件中的子包和模組的搜尋功能。

While this feature is not often needed, it can be used to extend the set of

modules found in a package.

這個功能可以用於擴充包中的模組集,不過它不常用。

.. rubric:: Footnotes

.. [#] In fact function definitions are also 'statements' that are 'executed'; the

   execuncution of a module-level function enter the funced symbol table.

.. [#]   事實上函數定義既是「宣告」又是「可執行體」;執行體由函數在模組全域語意表中的命名導入。

 以上就是Python 2.7基礎教學之:模組的內容,更多相關內容請關注PHP中文網(www.php.cn)!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn