Python 速查手冊

4.7 簡單陳述 import from as

本書已有新版,請參考 Python 簡易手冊 - 目錄

程式 (program) 中用來引入程式庫 (library) 的關鍵字 (keyword) 有 import 、 from 及 as , import 用來引入模組 (module) 的識別字 (identifier) 名稱, from 及 import 用來引入模組中指定的識別字,兩者都可以加上 as ,加上 as 後就能將原本模組中的名稱改成自訂的識別字。

這邊簡單示範在互動式介面引入標準程式庫 (standard library) 中的 random 模組, random 內含數學上處理隨機運算的相關定義, import random 後,就可以利用 random 加上小數點使用 random 內的定義,例如這裡呼叫 random 的 randint() 函數 (function) ,並提供兩個整數參數 (parameter) ,使 randint() 回傳兩個整數參數之間的整數

import random

print(random.randint(0, 9))

#《程式語言教學誌》的範例程式
# http://kaiching.org/
# 檔名:import01.py
# 功能:示範 import 、 from 、 as 陳述
# 作者:張凱慶

於命令列執行以上程式,結果如下

$ python3 import01.py
4
$

繼續看到用關鍵字 from 從 random 中引入 shuffle() 函數, shuffle() 用以攪亂陣列元素的順序,因為這裡是用 from random import shuffle ,因此可以直接使用 shuffle() 的名稱,不需要在 shuffle() 前加上 random 及小數點

from random import shuffle

a = list(range(10))
print(a)

shuffle(a)
print(a)

#《程式語言教學誌》的範例程式
# http://kaiching.org/
# 檔名:import02.py
# 功能:示範 import 、 from 、 as 陳述
# 作者:張凱慶

於命令列執行以上程式,結果如下

$ python3 import02.py
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[6, 8, 7, 3, 1, 4, 9, 2, 0, 5]
$

import 最後接上 as ,就把引入的模組庫名稱改成自訂的識別字,例如這裡把 random 的首字母改成大寫的識別字

import random as Random

print(Random.randint(0, 9))

#《程式語言教學誌》的範例程式
# http://kaiching.org/
# 檔名:import03.py
# 功能:示範 import 、 from 、 as 陳述
# 作者:張凱慶

於命令列執行以上程式,結果如下

$ python3 import03.py
3
$

from-import 最後也可以加上 as ,這樣就能把程式庫中的識別字改成自訂的名稱

from random import randint as Rint

print(Rint(0, 9))

#《程式語言教學誌》的範例程式
# http://kaiching.org/
# 檔名:import04.py
# 功能:示範 import 、 from 、 as 陳述
# 作者:張凱慶

於命令列執行以上程式,結果如下

$ python3 import04.py
5
$

相關教學影片

上一頁: 4.6 簡單陳述 continue
Python 速查手冊 - 目錄
下一頁: 4.8 簡單陳述 global
回 Python 教材首頁
回程式語言教材首頁