python模块
来源:互联网 发布:激光内雕机软件 编辑:程序博客网 时间:2024/05/21 05:57
本文译自https://docs.python.org/2.7/tutorial/。完全是出于个人兴趣翻译的,请勿追究责任。另外,谢绝商业牟利。刊印请与本人和原作者联系,无授权不得刊印,违者必究其责任。如需转发,请注明来源,并保留此行,尊重本人的劳动成果,谢谢。
来源:CSDN博客
作者:奔跑的QQEE
python 版本:2.7.13
(本文有删改)
python模块
一、综述
退出python解释器后再打开,上次写的所有方法,变量都已被销毁。如果想让命令保存更久,可将之以文本形式保存,而在执行时将内容读入。
python用一文件保存多个定义,而在另一python文件中调用它们。保存定义的文件叫作模块。模块间可互相调用。
模块不仅保存了定义,还保存了其它python语句。模块文件名是模块名加上后缀.py
。模块名可用全局变量__name__
得到。例,首先建一python文件,名为 fibo.py;
# fibo.pydef fib(n): a, b = 0, 1 while b < n: print b, a, b = b, a+bdef fib2(n): result = [] a, b = 0, 1 while b < n: result.append(b) a, b = b, a+b return result
然后,打开python 解释器。键入命令
>>> import fibo # 导入模块 fibo
调用 fibo.py 中定义的函数时,不应直接调用函数。正确的调用形式是模块名.函数名()
。例:
>>> 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'
如要经常使用某函数,应用一变量指向此函数。例:
>>> fib = fibo.fib>>> fib(500)1 1 2 3 5 8 13 21 34 55 89 144 233 377
二、细节
模块里的可执行语句用于初始化此模块。每个模块都有一个仅用于此模块的符号表。该符号表可被此模块中定义的所有方法使用。
不同模块可互相调用。被导模块名会加入到主调模块的全局变量表中。
有各种各样的imprt
语句。例:
>>> from fibo import fib, fib2 # 从 fibo 模块中导入fib,fib2>>> fib(500)1 1 2 3 5 8 13 21 34 55 89 144 233 377>>> from fibo import * #从 fibo 模块导入所有除下划线(_)开头的名称>>> fib(500)1 1 2 3 5 8 13 21 34 55 89 144 233 377
注意import * from 某模块/包
是不正确的语法。
如此运行python 文件时:
python fibo.py <arguments>
其中的代码将被执行。变量__name__
将被置为"__main__"
。如果在某块尾添加代码
if __name__ == "__main__": import sys fib(int(sys.argv[1]))
就可将该模块当作脚本文件执行。因为解析命令行的代码仅在该模块是主文件时运行。例:
$ python fibo.py 501 1 2 3 5 8 13 21 34
如果该模块已被导入,import fibo
将不起作用。
三、路径
假如要导入一叫 spam 的模块。解释器首先会根据此名称在内置模块中查找。若未找到
,会在sys.path
定义的目录列表中查找名为spam.py
的文件。
四、解释python(解释型语言)文件
spam.py
解释后的文件是spam.pyc
。该文件是spam.py
解释后的二进制文件,可快速响应python程序;其中不仅记录了解释后的python命令,而且还记录了文件的修改日期。若spam.py
与spam.pyc
的修改日期不一致,那么执行spam.py
时将忽略现存的spam.pyc
文件。
通常不用手动创建.pyc
文件。.py
文件解释成功后,解释器会尝试将编译后的二进制数据写入.pyc
文件中。若尝试失败并不出错;若由于某种原因未写入完全,此时的.pyc
文件是不合法的,执行.py
程序时将被忽略。
.pyc
文件具有平台无关性。因此python模块可在不同架构的机器上运行。
当python命令中加参数
-o
时,将会把.py
文件优化并存储在.pyo
文件中。例:python -O -m py_compile xx.py
传递两个
-o
参数表示进一步优化.py
文件。优化时将__doc__
从字节码中移除。但某些程序会依赖于此,因此有可能会导致程序出错。- 读取
.pyc
或.pyo
文件并不比读取.py
文件更快。使得执行.pyc
或.pyo
文件更快的原因是加载它们的速度更快。 - 让脚本执行更快的方法是将脚本中的代码置于一个或多个模块中,而添加一个导入了这些模块的很小的引导文件。
- 只有
.pyc
或.pyo
文件而没有.py
文件也是可以的。
五、标准模块
python有一标准模块库,有单独的文档来描述——python库参考(后来叫库参考)。一些模块已内置到了解释器中。例如,为windows操作系统提供了专门的winreg
模块;sys.ps1
sys.ps2
分别定义了第一,第二提示符。
>>> import sys>>> sys.ps1'>>> '>>> sys.ps2'... '>>> sys.ps1 = 'C> 'C> print 'Yuck!'Yuck!C>
这两个变量仅在解释器处在交互模式下才能定义。
变量sys.path
是一个规定了解释器搜索路径的字符串列表。默认取变量PYTHONPATH
规定的值;若此值未设定,则取系统规定的PYTHONPATH
值。可这样修改此值:
>>> import sys>>> sys.path.append('/ufs/guido/lib/python')
六、dir()函数
dir()
函数将列出待查模块中所有变量,模块,函数的名称,并以排序后的字符串列表形式返回。
>>> import fibo, sys>>> dir(fibo)['__name__', 'fib', 'fib2']>>> dir(sys) ['__displayhook__', '__doc__', '__excepthook__', '__name__', '__package__', '__stderr__', '__stdin__', '__stdout__', '_clear_type_cache', '_current_frames', '_getframe', '_mercurial', 'api_version', 'argv', 'builtin_module_names', 'byteorder', 'call_tracing', 'callstats', 'copyright', 'displayhook', 'dont_write_bytecode', 'exc_clear', 'exc_info', 'exc_traceback', 'exc_type', 'exc_value', 'excepthook', 'exec_prefix', 'executable', 'exit', 'flags', 'float_info', 'float_repr_style', 'getcheckinterval', 'getdefaultencoding', 'getdlopenflags', 'getfilesystemencoding', 'getobjects', 'getprofile', 'getrecursionlimit', 'getrefcount', 'getsizeof', 'gettotalrefcount', 'gettrace', 'hexversion', 'long_info', 'maxint', 'maxsize', 'maxunicode', 'meta_path', 'modules', 'path', 'path_hooks', 'path_importer_cache', 'platform', 'prefix', 'ps1', 'py3kwarning', 'setcheckinterval', 'setdlopenflags', 'setprofile', 'setrecursionlimit', 'settrace', 'stderr', 'stdin', 'stdout', 'subversion', 'version', 'version_info', 'warnoptions']
若没有指定参数,dir()将返回当前程序中定义的所有内容。
>>> a = [1, 2, 3, 4, 5]>>> import fibo>>> fib = fibo.fib>>> dir()['__builtins__', '__name__', '__package__', 'a', 'fib', 'fibo', 'sys']
dir()
并不会返回内置的函数名和变量名。若要返回,应引入模块__builtin__
。
>>> import __builtin__>>> dir(__builtin__) ['ArithmeticError', 'AssertionError', 'AttributeError', 'BaseException', 'BufferError', 'BytesWarning', 'DeprecationWarning', 'EOFError', 'Ellipsis', 'EnvironmentError', 'Exception', 'False', 'FloatingPointError', 'FutureWarning', 'GeneratorExit', 'IOError', 'ImportError', 'ImportWarning', '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', 'UnicodeWarning', 'UserWarning', 'ValueError', 'Warning', 'ZeroDivisionError', '_', '__debug__', '__doc__', '__import__', '__name__', '__package__', 'abs', 'all', 'any', 'apply', 'basestring', 'bin', 'bool', 'buffer', 'bytearray', 'bytes', 'callable', 'chr', 'classmethod', 'cmp', 'coerce', 'compile', 'complex', 'copyright', 'credits', 'delattr', 'dict', 'dir', 'divmod', 'enumerate', 'eval', 'execfile', 'exit', 'file', 'filter', 'float', 'format', 'frozenset', 'getattr', 'globals', 'hasattr', 'hash', 'help', 'hex', 'id', 'input', 'int', 'intern', 'isinstance', 'issubclass', 'iter', 'len', 'license', 'list', 'locals', 'long', 'map', 'max', 'memoryview', 'min', 'next', 'object', 'oct', 'open', 'ord', 'pow', 'print', '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']
七、包
包使得python模块的命名空间结构化。例,A.B
表明B模块包含于A模块。看个例子:
sound/ #最顶级的包,sound __init__.py #sound包的初始化文件,没有此文件sound便不是包 formats/ #子包formats __init__.py wavread.py wavwrite.py aiffread.py aiffwrite.py auread.py auwrite.py ... effects/ #子包effects __init__.py #子包的初始化文件,没有此文件effects便不是包 echo.py surround.py reverse.py ... filters/ #子包filters __init__.py #子包的初始化文件,没有此文件filters便不是包 equalizer.py vocoder.py karaoke.py ...
导入包时,python会根据sys.path
定义的路径搜索包。
__init__.py
存在时,对应目录才能算是包。该文件可为空。
可导入包中的某个模块,例:
import sound.effects.echo
调用某方法时用完整名,
sound.effects.echo.echofilter(input, output, delay=0.7, atten=4)
另一种方法是:
from sound.effects import echo
调用某方法时可这样做:
echo.echofilter(input, output, delay=0.7, atten=4)
也可用第二种方法直接导入某方法:
from sound.effects.echo import echofilter
调用时这样做:
echofilter(input, output, delay=0.7, atten=4)
注意:用格式from 包 import 项
导入项时,项可以是子模块、子包、函数名、类名,变量名。导入前首先检测是否存在指定项。若没有,系统假定指定项是个模块并尝试导入它。查无此项便失败,返回ImportError
类型的异常。而用格式import 项.子项.子项的子项
导入项时,除最后一项外,其他项必须是包,而最后一项可以是模块,也可以是包,但不能是上一项中定义的类,函数,变量。
八、import * from 包
想象下用from sound.effects import *
会发生什么?理论上会找到出现在包中的子模块,然后将它们全部导入。这要花费很长事件,而且可能会出现意想不到的问题。
如果__init__.py
文件中定义了名为__all__
的列表,那么就会将__all__
中规定的模块导入。例:
#sound/effects/__init__.py__all__ = ["echo", "surround", "reverse"]
执行命令
from sound.effects import *
将导入sound/effects 包中三个名为echo
,surround
,reverse
的模块。
如果没有定义__all__
列表,from sound.effects import *
不会将sound/effects
下的所有子模块导入,只是将包sound.effects
导入。
事实上,推荐使用from 包 import 指定模块
,因为有时需要导入不同包内同名的模块。
九、包内引用
子模块间经常需要互相引用。
例如,surrond
模块可能要引用echo
模块。surrond
模块只需使用import echo
或from echo import sth
即可。如果当前包内找不到被导模块,那么就去上级模块查找。
再如,如果模块sound.filters.vocoder
需要引用sound.effects
中的echo
模块,只需这样做:
from sound.effects import echo
- python模块 ---logging模块
- python模块-re模块
- python模块 - functools模块
- python 模块 模块文件
- python模块 - pickle模块
- python模块 - copy模块
- python模块
- python 模块
- python-模块
- python 模块
- python模块
- python 模块
- python模块
- python 模块
- python 模块
- 模块-python
- python 模块
- python模块
- 利用JSON解析函数
- hive中文乱码问题
- matter.js学习笔记(四)--Constraint.create()制造跷跷板
- 代码质量管控的四个阶段
- python3 子进程和父进程
- python模块
- Flink入门教程--Component Stack
- android获取存储目录(路径)的几种方式和注意事项
- 解决myEclipse未保存完全后导致打不开的问题
- JAVA的MVC设计模式
- linux 内核container_of
- 用户访问端 移动端,PC端,微信等常用平台和浏览器判断
- 239. Sliding Window Maximum 滑动窗口最大值
- mysql导出数据乱码