What is the difference between Python's import statement and from...import...?

In Python, importboth statements and from...import...statements are used to import a module or specific content within a module. The differences between them are as follows:

importstatement:

  • importstatement is used to import an entire module or package.
  • When using importa statement to import a module, you need to use the module name as a prefix when using the content in the module.

from...import...statement:

  • from...import...statement is used to import specified content from a module.
  • You can use fromkeywords to specify which modules to import, and then use importkeywords to specify specific things to import.
  • After using from...import...the statement to import content, you can use the imported content directly without using the module name as a prefix.
  • Example:from module_name import object_name

Here are some more concrete examples to help understand the difference between the two:

# 使用import语句导入整个模块
import math
print(math.sqrt(16))  # 使用模块名作为前缀

# 使用from...import...语句导入特定内容
from math import sqrt
print(sqrt(16))  # 直接使用导入的内容,无需使用模块名作为前缀

# 使用import语句导入整个模块,并为模块指定别名
import numpy as np
array = np.array([1, 2, 3])
print(array)

# 使用from...import...语句导入特定内容,并为内容指定别名
from numpy import array as np_array
array = np_array([1, 2, 3])
print(array)

In general, importstatements apply to importing entire modules or packages, while from...import...statements apply to importing specific things from modules and using them. The choice of which statement to use depends on the needs of your code and personal preference.

Guess you like

Origin blog.csdn.net/wenhao_ir/article/details/131343089