企业🤖AI Agent构建引擎,智能编排和调试,一键部署,支持私有化部署方案 广告
前面我们大部分代码都在 IDLE 中书写运行,如果我们关闭了 IDLE ,那么我们写的代码就都消失了。为了保留我们书写的代码,我们将代码保存到 .py 文件中,以便长久使用。同时又有一个问题,在一个 .py 文件中,如果写了10000行代码,那每次我们查看代码将会非常费劲。为了解决这个问题,我们将大型的程序分割成多个包含 Python 代码的文件(.py),每一个文件都是一个模块。 模块是一个包含所有你定义的函数和变量的文件,其后缀名是 .py。模块可以被别的程序引入,以使用该模块中的函数等功能。这也是使用 Python 标准库的方法。 根据来源,模块分类: * Python 内置模块 * 第三方模块 * 自定义模块 ***** [TOC] ***** # 5.1 import 要使用某一个模块,需先导入该模块到你的文件中,语法如下: ``` import module_name ``` 比如,前面我们为了查看关键字使用的模块: ``` import keyword print(keyword.kwlist) ``` ``` # Out: ['False', 'None', 'True', 'and', 'as', 'assert', 'async', 'await', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield'] ``` Python 内置模块直接导入使用即可,第三方模块则需要通过 `pip` 命令安装后才能使用。我们的自定义模块直接放到我们要使用它的文件同一目录即可。 ***** # 5.2 from...import Python 的 from...import 语句让你从模块中导入一个指定的部分到当前命名空间中,语法如下: ``` from module_name import name1[, name2[, ... nameN]] ``` 把一个模块的所有内容全都导入到当前的命名空间也是可行的,只需使用如下声明: ``` from module_name import * ``` **实例:使用自己定义的模块** *注意:两个文件应该在同一目录下* 首先,创建一个斐波那契数列模块 fibo.py ,代码如下: ``` # 斐波那契(fibonacci)数列模块 # 返回到 n 的斐波那契数列 def fib(n): a, b = 0, 1 while b < n: print(b, end=' ') a, b = b, a+b print() # 返回到 n 的斐波那契数列到列表中 def fib_list(n): result = [] a, b = 0, 1 while b < n: result.append(b) a, b = b, a+b return result ``` 然后,新建一个测试文件 fibo_test.py 来使用自定义模块: ``` from fibo import fib, fib_list fib(50) print(fib_list(50)) ``` ``` # Out: 1 1 2 3 5 8 13 21 34 [1, 1, 2, 3, 5, 8, 13, 21, 34] ``` **dir()** Python 内置函数,可以找到模块内定义的所有名称。以一个字符串列表的形式返回: ``` >>> import sys >>> dir(sys) ['__breakpointhook__', '__displayhook__', '__doc__', '__excepthook__', '__interactivehook__', '__loader__', '__name__', '__package__', '__spec__', '__stderr__', '__stdin__', '__stdout__', '_clear_type_cache', '_current_frames', '_debugmallocstats', '_enablelegacywindowsfsencoding', '_framework', '_getframe', '_git', '_home', '_xoptions', 'api_version', 'argv', 'base_exec_prefix', 'base_prefix', 'breakpointhook', 'builtin_module_names', 'byteorder', 'call_tracing', 'callstats', 'copyright', 'displayhook', 'dllhandle', 'dont_write_bytecode', 'exc_info', 'excepthook', 'exec_prefix', 'executable', 'exit', 'flags', 'float_info', 'float_repr_style', 'get_asyncgen_hooks', 'get_coroutine_origin_tracking_depth', 'get_coroutine_wrapper', 'getallocatedblocks', 'getcheckinterval', 'getdefaultencoding', 'getfilesystemencodeerrors', 'getfilesystemencoding', 'getprofile', 'getrecursionlimit', 'getrefcount', 'getsizeof', 'getswitchinterval', 'gettrace', 'getwindowsversion', 'hash_info', 'hexversion', 'implementation', 'int_info', 'intern', 'is_finalizing', 'maxsize', 'maxunicode', 'meta_path', 'modules', 'path', 'path_hooks', 'path_importer_cache', 'platform', 'prefix', 'set_asyncgen_hooks', 'set_coroutine_origin_tracking_depth', 'set_coroutine_wrapper', 'setcheckinterval', 'setprofile', 'setrecursionlimit', 'setswitchinterval', 'settrace', 'stderr', 'stdin', 'stdout', 'thread_info', 'version', 'version_info', 'warnoptions', 'winver'] ``` 注:sys 是Python内置模块,后续会学习