环境:python 2.7.11,python3.5基本相同。
Contents
[TOC]
Python Module
模块可以包括函数定义以及一些语句(用于初始化模块,因此只在第一次import语句被执行时调用)。
模块拥有私有的符号表(作为模块内所有函数的全局符号表),所以在编写模块时可以不用担心与用户的全局变量发生命名冲突的情况。
Import Module
# ./fibo.py
# ./main.py
# main.py
from fibo import fib
or
import fibo
fib = fibo.fib
值得一提的是,在module中也可以定义__all__(见下文)
另外除非在__all__加入,import会自动忽略以_开头的函数。
Packages
包是一种组织模块命名空间的方式。
For example, the module name A.B designates a submodule named B in a package named A.
example
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
...
__init__.py
含有__init__.py文件的文件夹才会被Python认为是一个包。__init__.py 可以为空,也可以有用于初始化包的语句。
When import individual modules from the package, it must be referenced with its full name.
Import:
import sound.effects.echo
When Use:
sound.effects.echo.echofilter(input, output, delay=0.7, atten=4)
import * from a package
When
from sound.effects import *
理想情况下,这个语句会遍历整个文件夹,然后import全部模块。但是,这不是python的实现方式。
因此需要在__init__.py中显式地定义名为__all__的list。此时上述语句会import``__all__中的所有模块。
all = ["echo", "surround", "reverse"]
If __all__ is not defined, the statement from sound.effects import * does not import all submodules from the package sound.effects into the current namespace; it only ensures that the package sound.effects has been imported (possibly running any initialization code in __init__.py) and then imports whatever names are defined in the package.
**This **includes:
any names defined (and submodules explicitly loaded) by __init__.py.
any submodules of the package that were explicitly loaded by previous import statements.
For example:
import sound.effects.echo
import sound.effects.surround
from sound.effects import *
In this example, the echo and surround modules are imported in the current namespace because they are defined in the sound.effects package when the from...import statement is executed.
Intra-package References
When packages are structured into subpackages (as with the sound package in the example), you can use absolute imports as well as relative imports
Explicit relative import
from . import echo
from .. import formats
from ..filters import equalizer
Reference
To learn more, look up the DOCs @here