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
广告
© . All rights reserved.