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