前面我們大部分代碼都在 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內置模塊,后續會學習