The Python Tutorial 6——Modules

update 2015.1.21

A module is a file containing Python definitions and statements. The file name is the module name with the suffix.py appended. Within a module, the module’s name (as a string) is available as the value of the global variable__name__. For instance, use your favorite text editor to create a file called fibo.py in the current directory with the following contents:

# Fibonacci numbers module

def fib(n):    # write Fibonacci series up to n
    a, b = 0, 1
    while b < n:
        print b,
        a, b = b, a+b

def fib2(n): # return Fibonacci series up to n
    result = []
    a, b = 0, 1
    while b < n:
        result.append(b)
        a, b = b, a+b
    return result

Now enter the Python interpreter and import this module with the followingcommand:

>>> import fibo
This does not enter the names of the functions defined in fibo directly in the current symbol table; it only enters the module name fibo there. Using the module name you can access the functions:  模块名.方法名 形式调用

>>> fibo.fib(1000)
1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987
>>> fibo.fib2(100)
[1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
>>> fibo.__name__
'fibo'

If you intend to use a function 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

6.1. 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 name is encountered in an import statement.

There is a variant of the import statement that imports names from a module directly into the importing module’s symbol table. For example:

>>> from fibo import fib, fib2
>>> fib(500)
1 1 2 3 5 8 13 21 34 55 89 144 233 377

This does not introduce the module name from which the imports are taken in the local symbol table (so in the example,fibo is not defined).

6.1.1. Executing modules as scripts

主要讲如何设置模块为可执行脚本,在模块末尾添加if语句即可

When you run a Python module with

python fibo.py <arguments>

the code in the module will be executed, just as if you imported it, but with the__name__ set to"__main__". That means that by adding this code at the end of your module:

def fibo(n):
	a, b = 0, 1
	while b < n:
		print b
		a, b = b, a + b

def fibo2(n):
	result = []
	a, b = 0, 1
	while b < n:
		result.append(b)
		a, b = b, a + b
	return result

if __name__ == '__main__':
	import sys
	fibo(int(sys.argv[1]))

you can make the file usable as a script as well as an importable module,because the code that parses the command line only runs if the module is executed as the “main” file:

$ python fibo.py 50
1 1 2 3 5 8 13 21 34

If the module is imported, the code is not run:

>>> import fibo
>>>

6.1.2. The Module Search Path

模块导入路径顺序,先built-in,找不到再从sys.path查找

When a module named spam is imported, the interpreterfirst searches for a built-in module with that name. If not found, it then searches for a file named spam.py in a list of directories given by the variablesys.path.sys.path is initialized from these locations:

  • the directory containing the input script (or the current directory).
  • PYTHONPATH (a list of directory names, with the same syntax as the shell variable PATH).
  • the installation-dependent default.

After initialization, Python programs can modify sys.path. The directory containing the script being run is placed at the beginning of the search path, ahead of the standard library path. This means that scripts in that directory will be loaded instead of modules of the same name in the library directory. This is an error unless the replacement is intended. See sectionStandard Modules for more information.

6.1.3. “Compiled” Python files

As an important speed-up of the start-up time for short programs that use a lot of standard modules, if a file called spam.pyc exists in the directory where spam.py is found, this is assumed to contain an already-“byte-compiled” version of the module spam.
Normally, you don’t need to do anything to create the spam.pyc file.Whenever spam.py is successfully compiled, an attempt is made to write the compiled version to spam.pyc.

6.2. Standard Modules

Python comes with a library of standard modules, described in a separate document, the Python Library Reference.

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 PYTHONPATH, or from a built-in default if PYTHONPATH is not set. You can modify it using standard list operations:

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

6.3. The dir() Function

The built-in function dir() is used to find out which names a module defines. It returns a sorted list of strings.  列出一个模块所有属性信息。

6.4. Package

Packages are a way of structuring Python’s module namespace by using “dotted module names”. For example, the module name A.B designates a submodule namedB in a package namedA.  包的目的:代码重用、便于扩展、域的划分,避免变量重名

一个包结构

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
              ...

Users of the package can import individual modules from the package, for example: 包的两种导入方式  1)import   包名.子包名       2)from  包名   import  子包名

import sound.effects.echo

This loads the submodule sound.effects.echo. It must bereferenced withi ts full name.

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 echo, and makes it available without its package prefix, so it can be used as follows:

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 echo, but this makes its function echofilter() directly available:

echo filter(input, output, delay=0.7, atten=4)

Note that when using frompackageimport item, the item can be either a submodule (or subpackage) of the package, or some other name defined in the package, like afunction, 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, anImportError exception is raised.

Contrarily, when using syntax like importitem.subitem.subsubitem, each item except for the last must be a package; the last item can be a module or a package butcan’t be a class or function or variable defined in the previous item.

6.4.1. Importing * From a Package

不推荐使用这种方式,可能带来副作用,比如变量重名等

6.4.2. Intra-package References

同一个包下子包可以相互引用

1)绝对路径引用

When packages are structured into subpackages (as with the sound package in the example), you can use absolute imports to refer to submodules of siblings packages. For example, if the modulesound.filters.vocoder needs to usetheecho module in thesound.effects package, it can usefrom sound.effectsimport echo.

2) 相对路径引用

Starting with Python 2.5, in addition to the implicit relative imports described above, you can writeexplicit relative imports with the from module import name form of import statement. These explicit relative importsuse leading dots to indicate the current and parent packages involved in the relative import. From thesurround module for example, you might use:

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 shouldalways use absolute imports.

6.4.3. Packages in Multiple Directories

not often needed

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值