Python 的 from 關鍵字



Python 的 from 關鍵字用於從模組、類或函式中匯入特定部分。它是一個區分大小寫的關鍵字。如果沒有import關鍵字,我們就不能使用from,因為兩者是相互依賴的,否則會引發SyntaxError

用法

以下是 Python from 關鍵字的用法:

from <module> import <function>

其中:

  • module 是模組的名稱。
  • function 是我們需要匯入的函式。

示例

以下是 Python from 關鍵字的基本示例:

# Importing specific functions
from math import sqrt, pow
# Using the imported functions
print("Square root of 81 is:", sqrt(81))  
print("5 to the power of 3 is:", pow(5, 3))  

輸出

以下是上述程式碼的輸出:

Square root of 81 is: 9.0
5 to the power of 3 is: 125.0

在沒有 'import' 的情況下使用 from 關鍵字

當我們不使用import關鍵字而使用from關鍵字時,它會引發SyntaxError

示例

在下面的示例中,我們沒有與from一起使用import關鍵字:

# Importing the datetime class from the datetime module
from datetime  datetime
print(datetime.now()) 

輸出

以下是上述程式碼的輸出:

File "/home/cg/root/47560/main.py", line 2
    from datetime  datetime
                   ^^^^^^^^
SyntaxError: invalid syntax

使用 from 關鍵字匯入整個模組

我們還可以使用from關鍵字和import後跟星號[*]來匯入模組中的所有函式。

示例

這是一個使用from關鍵字匯入模組中所有函式的示例:

from math import *
print("The remainder of 16 when divided by 7 :",remainder(16,7))
print("The sine value of 90:",sin(90))

輸出

以下是上述程式碼的輸出:

The remainder of 16 when divided by 7 : 2.0
The sine value of 90: 0.8939966636005579

將 from 關鍵字與 'as' 一起使用

我們還可以將as關鍵字與from一起使用,為特定函式建立選定的名稱。

示例

以下是from關鍵字與as關鍵字一起使用的示例:

# Importing a class and renaming it
from datetime import datetime as dt
# Using the renamed class
print("Current date and time:", dt.now()) 

輸出

以下是上述程式碼的輸出:

Current date and time: 2024-08-07 11:54:06.534770
python_keywords.htm
廣告