環(huán)境:python 2.7.11,python3.5基本相同。
Contents
[TOC]
Python Module
模塊可以包括函數(shù)定義以及一些語(yǔ)句(用于初始化模塊,因此只在第一次import語(yǔ)句被執(zhí)行時(shí)調(diào)用)。
模塊擁有私有的符號(hào)表(作為模塊內(nèi)所有函數(shù)的全局符號(hào)表),所以在編寫(xiě)模塊時(shí)可以不用擔(dān)心與用戶(hù)的全局變量發(fā)生命名沖突的情況。
Import Module
# ./fibo.py
# ./main.py
# main.py
from fibo import fib
or
import fibo
fib = fibo.fib
值得一提的是,在module中也可以定義__all__(見(jiàn)下文)
另外除非在__all__加入,import會(huì)自動(dòng)忽略以_開(kāi)頭的函數(shù)。
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文件的文件夾才會(huì)被Python認(rèn)為是一個(gè)包。__init__.py 可以為空,也可以有用于初始化包的語(yǔ)句。
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 *
理想情況下,這個(gè)語(yǔ)句會(huì)遍歷整個(gè)文件夾,然后import全部模塊。但是,這不是python的實(shí)現(xiàn)方式。
因此需要在__init__.py中顯式地定義名為__all__的list。此時(shí)上述語(yǔ)句會(huì)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