1. 程式人生 > 其它 >Python-import和from import的使用

Python-import和from import的使用

技術標籤:Pythonpython

import moduleName1[,moduleName2[...]]
import math
print(math.sqrt(25))
print(math.pi)
這種方法一次可匯入多個模組。但在使用模組中的類、函式、變數等內容時,需要在它們前面加上模組名。
from moduleName import *
from math import *
print(sqrt(25))
print(pi)
這種方法一次匯入一個模組中的所有內容。使用時不需要新增模組名為字首,但是程式的可讀性較差。
from moduleName import
object1[,object2[...]]
from math import sqrt,e
print(e)
print(sqrt(25))
這種方法一次匯入一個模組中指定內容,如某個函式。呼叫時不需要新增模組名為字首。使用這種方法的程式可讀性介於前兩者之間。
上述程式中 from math import sqrt,e 表示匯入模組math中的sqrt函式和變數e,程式中只可以使用sqrt函式和e的值,不能使用該模組中的其他內容。