'... '
>>> sys.ps1 = 'C> '
C> print 'Yuck!'
Yuck!
C>
These two variables are only defined if the interpreter 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
environment variable :envvar:`PYTHONPATH`, or from 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__', '__excepthook__', '__name__', '__stderr__',
'__stdin__', '__stdout__', '_getframe', 'api_version', 'argv',
'builtin_module_names', 'byteorder', 'callstats', 'copyright',
'displayhook', 'exc_clear', 'exc_info', 'exc_type', 'excepthook',
'exec_prefix', 'executable', 'exit', 'getdefaultencoding', 'getdlopenflags',
'getrecursionlimit', 'getrefcount', 'hexversion', 'maxint', 'maxunicode',
'meta_path', 'modules', 'path', 'path_hooks', 'path_importer_cache',
'platform', 'prefix', 'ps1', 'ps2', 'setcheckinterval', 'setdlopenflags',
'setprofile', 'setrecursionlimit', 'settrace', 'stderr', 'stdin', 'stdout',
'version', 'version_info', 'warnoptions']
Without arguments, :func:`dir` lists the names you have defined currently:
无参数调用时, :func:`dir` 函数返回当前定义的命名 ::
>>> a = [1, 2, 3, 4, 5]
>>> import fibo
>>> fib = fibo.fib
>>> dir()
['__builtins__', '__doc__', '__file__', '__name__', 'a', 'fib', 'fibo', '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
want a list of those, they are defined in the standard module
:mod:`__builtin__`:
:func:`dir` 不会列出内置函数和变量名。如果你想列出这些内容,它们在标准模块
:mod:`__builtin__` 中定义 ::
>>> import __builtin__
>>> dir(__builtin__)
['ArithmeticError', 'AssertionError', 'AttributeError', 'DeprecationWarning',
'EOFError', 'Ellipsis', 'EnvironmentError', 'Exception', 'False',
'FloatingPointError', 'FutureWarning', 'IOError', 'ImportError',
'IndentationError', 'IndexError', 'KeyError', 'KeyboardInterrupt',
'LookupError', 'MemoryError', 'NameError', 'None', 'NotImplemented',
'NotImplementedError', 'OSError', 'OverflowError',
'PendingDeprecationWarning', 'ReferenceError', 'RuntimeError',
'RuntimeWarning', 'StandardError', 'StopIteration', 'SyntaxError',
'SyntaxWarning', 'SystemError', 'SystemExit', 'TabError', 'True',
'TypeError', 'UnboundLocalError', 'UnicodeDecodeError',
'UnicodeEncodeError', 'UnicodeError', 'UnicodeTranslateError',
'UserWarning', 'ValueError', 'Warning', 'WindowsError',
'ZeroDivisionError', '_', '__debug__', '__doc__', '__import__',
'__name__', 'abs', 'apply', 'basestring', 'bool', 'buffer',
'callable', 'chr', 'classmethod', 'cmp', 'coerce', 'compile',
'complex', 'copyright', 'credits', 'delattr', 'dict', 'dir', 'divmod',
'enumerate', 'eval', 'execfile', 'exit', 'file', 'filter', 'float',
'frozenset', 'getattr', '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 :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 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 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):
假设你现在想要设计一个模块集(一个“包”)来统一处理声音文件和声音数据。
存在几种不同的声音格式(通常由它们的扩展名来标识,例如: :file:`.wav`
, :file:`.aiff` , :file:`.au` ),于是,为了在不同类型的文件格式之间
转换,你需要维护一个不断增长的包集合。可能你还想要对声音数据做很多不同
的操作(例如混音,添加回声,应用平衡功能,创建一个人造效果),所以你要
加入一个无限流模块来执行这些操作。你的包可能会是这个样子(通过分级的文
件体系来进行分组) ::
sound/ Top-level package
__init__.py Initialize the sound package
formats/ Subpackage for file format conversions
__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 package subdirectory.
导入模块时,Python通过 ``sys.path`` 中的目录列表来搜索存放包的子目录。
The :file:`__init__.py` files are required to make Python treat the directories
as containing packages; this is done to prevent 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.
必须要有一个 :file:`__init__.py` 文件的存在,才能使 Python 视该目录为
一个包;这是为了防止某些目录使用了 ``string`` 这样的通用名而无意中在随
后的模块搜索路径中覆盖了正确的模块。最简单的情况下,
:file:`__init__.py` 可以只是一个空文件,不过它也可能包含了包的初始化代码,或者设置了 ``__all__`` 变量,后面会有相关介绍。
Users of the package can import individual modules from the package, for
example:
包用户可以从包中导入合法的模块,例如 ::
import sound.effects.echo
This loads the submodule :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:
导入包时有一个可以选择的方式 ::
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:
这样就加载了 :mod:`echo` 子模块,并且使得它在没有包前缀的情况下也可以
使用,所以它可以如下方式调用 ::
echo.echofilter(input, output, delay=0.7, atten=4)
Yet another variation is to import the desired function or variable directly:
还有另一种变体用于直接导入函数或变量 ::
from sound.effects.echo import echofilter
Again, this loads the submodule :mod:`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 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.
需要注意的是使用 ``from package import item`` 方式导入包时,这个子项(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 a
package but can't be a class or function or variable defined in the previous
item.
相反,使用类似 ``import item.subitem.subsubitem`` 这样的语法时,这些子项必
须是包,最后的子项可以是包或模块,但不能是前面子项中定义的类、函数或变
量。
.. _tut-pkg-import-star:
Importing /* From a Package
---------------------------
.. index:: single: __all__
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.
那么当用户写下 ``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
: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:`sounds/effects/__init__.py` 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.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:
如果没有定义 ``__all__`` , ``from Sound.Effects import *`` 语句不会从
:mod:`sound.effects` 包中导入所有的子模块。无论包中定义多少命名,只能
确定的是导入了 :mod:`sound.effects` 包(可能会运行 __init__.py 中的初
始化代码)以及包中定义的所有命名会随之导入。这样就从 ``__init__.py``
中导入了每一个命名(以及明确导入的子模块)。同样也包括了前述的
:keyword:`import` 语句从包中明确导入的子模块,考虑以下代码 ::
import sound.effects.echo
import sound.effects.surround
from 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 :mod:`sound.effects` package
when 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
production code.
尽管某些模块设计为使用 ``import *`` 时它只导出符全某种模式的命名,仍然
不建议在生产代码中使用这种写法。
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.
记住, ``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
references are so common that the :keyword:`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 a top-level module with the given name.
子模块之间经常需要互相引用。例如,: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 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``.
如果包中使用了子包结构(就像示例中的 :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`` form of import statement. These explicit relative 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:
从 Python 2.5 开始,前述的这种内部的显式相对位置导入得到改进,你可以用这样
的形式 ``from module import name`` 来写显式的相对位置导入。那些显式相
对导入用点号标明关联导入当前和上级包。以 :mod:`surround` 模块为例,你可以
这样用 ::
from . import echo
from .. import formats
from ..filters import equalizer
Note that both explicit and implicit relative imports 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 module of a Python application should
always use absolute imports.
需要注意的是显式或隐式相对位置导入都基于当前模块的命名。因为主模块的名
字总是 ``"__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 modules and
subpackages contained in the package.
包支持一个更为特殊的特性, :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
execution of a module-level function enters the function name in the module's
global symbol table.
.. [#] 事实上函数定义既是“声明”又是“可执行体”;执行体由函数在模块全局语义表中的命名导入。
以上就是Python 2.7基础教程之:模块的内容,更多相关内容请关注PHP中文网(HdhCmsTestgxlcms测试数据)!
查看更多关于Python2.7基础教程之:模块的详细内容...