6.模块

模块介绍


  • 随着程序变长,您可能需要将其分成几个文件以便于维护。您可能还想使用您在几个程序中编写的方便功能,而不将其定义复制到每个程序中。
  • 为了支持这一点,Python有一种方法可以将定义放在文件中,并在脚本或解释器的交互式实例中使用它们。这样的文件被称为 模块 ; 可以将模块中的定义导入到其他模块或主模块(在顶层和计算器模式下执行的脚本中可访问的变量集合)。

  • 模块是一个包含Python定义和语句的文件。文件名是带有后缀的模块名称.py。在模块中,模块的名称(作为字符串)可用作全局变量的值 name。例如,使用您最喜欢的文本编辑器创建一个fibo.py在当前目录中调用的文件,其中包含以下内容:

# Fibonacci numbers module

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

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
    # 输入Python解释器并使用以下命令导入此模块
    import fibo

  • 更多关于模块
    • from fibo import fib, fib2
    • from fibo import * ( 不推荐)
    • import fibo as fib
  • 注意:
    • 注意 出于效率原因,每个模块仅在每个解释器会话中导入一次。因此,如果您更改模块,则必须重新启动解释器或者,如果它只是一个要交互测试的模块,请使用importlib.reload(),例如:import importlib; importlib.reload(modulename)
  • 执行模块作为脚本
# 当你运行一个python 模块时
$ python fibo.py <arguments>
# 模块中的代码将被执行,就像您导入它一样,但__name__设置为"__main__"。
# 这意味着通过在你的模块的末尾添加这个代码:
if __name__ == "__main__":
    import sys
    fib(int(sys.argv[1]))
# 您可以将该文件作为脚本以及可导入模块使用,因为仅当模块作为“主”文件执行时,
# 才会运行解析命令行的代码
$ python fibo.py 50
1 1 2 3 5 8 13 21 34

# 这通常用于为模块提供方便的用户界面,或者用于测试目的
# (在脚本执行测试套件时运行模块)
  • 模块搜索路径
  • 编译Python 文件
    • 为了加速加载模块,Python将每个模块的编译版本缓存在pycache名称下的目录中,其中版本对编译文件的格式进行编码;它通常包含Python版本号。
    • 在两种情况下,Python不会检查缓存
      • 首先,它总是重新编译并且不存储从命令行直接加载的模块的结果。
      • 其次,如果没有源模块,它不会检查缓存。

Some tips for experts:

You can use the -O or -OO switches on the Python command to reduce the size of a compiled module. The -O switch removes assert statements, the -OO switch removes both assert statements and doc strings. Since some programs may rely on having these available, you should only use this option if you know what you’re doing. “Optimized” modules have an opt- tag and are usually smaller. Future releases may change the effects of optimization.
A program doesn’t run any faster when it is read from a .pyc file than when it is read from a .py file; the only thing that’s faster about .pyc files is the speed with which they are loaded.
The module compileall can create .pyc files for all modules in a directory.
There is more detail on this process, including a flow chart of the decisions, in PEP 3147.

  • 标准模块
  • dir 功能
# 内置函数dir()用于找出模块定义的名称。它返回一个字符串的排序列表:
>>> import fibo, sys
>>> dir(fibo)
['__name__', 'fib', 'fib2']
>>> import fibo, sys
>>> dir(fibo)
['__name__', 'fib', 'fib2']

# 如果没有参数,dir()列出当前定义的名称
>>> a = [1, 2, 3, 4, 5]
>>> import fibo
>>> fib = fibo.fib
>>> dir()
['__builtins__', '__name__', 'a', 'fib', 'fibo', 'sys']
# 列出了所有类型的名称:变量,模块,函数等


  • 软件包
  • Importing * From a Package
  • 等 略

猜你喜欢

转载自blog.csdn.net/importpd/article/details/80054515