如何從一個 Python 模組匯入單個函式?


你可以使用“from module import function”語句從一個 Python 模組中匯入一個特定的函式。例如,如果你想從 math 庫中匯入 sin 函式而不匯入任何其他函式,你可以這樣做

>>> from math import sin
>>> sin(0)
0.0

注意你不需要給 sin 加上“math.”字首,因為只匯入了 sin 而不是 math。此外你也可以用別名表示匯入的函式。例如,

>>> from math import cos as cosine
>>> cosine(0)
1.0

更新日期: 30-9 月-2019

10K+ 瀏覽

開啟你的 職業

透過完成課程獲得認證

開始
廣告