[Python] module import ③ (module import syntax | from import part of the module function | set an alias for the imported module | import import module set alias | from import module set alias )





1. Import part of the content of the module - from import part of the module function




1. From imports some module functions


When importing a module, sometimes you don’t need to use the complete functions of the module, you only need to import some of the specified functions, which also conforms to the principle of least knowledge design;

from import part of module function syntax:

from module_name import specific_name

module_name is the module name;

specific_name is the function name specified in the module;


Modules imported in this way will only import some of the specified functions in the module. After importing, they can be directly accessed using the function names specified in the specific_name module;

It is not necessary to use to access before accessing 模块名称.功能名称();


2. Code example - from Import some module functions


In the following code, the sleep function in the time module is imported. After importing, the sleep function can be called directly, and the method must be used time.sleepto call;


Code example:

"""
异常传递 代码示例
"""
# 导入时间模块
from time import sleep

print("开始执行")

# 调用模块方法 直接使用 功能名称即可
# 使用时间模块的 sleep 休眠功能
sleep(3)

print("结束执行")

Results of the :

D:\001_Develop\022_Python\Python39\python.exe D:/002_Project/011_Python/HelloPython/Hello.py
开始执行
结束执行

Process finished with exit code 0

insert image description here





2. Set an alias for the imported module




1. Set alias syntax


In Python, you can also set aliases for imported modules/module functions. The syntax for setting aliases is as follows:

import module_name as renamed_name
from module_name import specific_name as renamed_name

module_name is the module name;

specific_name is part of the function of the module;

renamed_name is an alias set for some functions of the module;

This usage can import the module or the specific_name function in the module into the current namespace, and rename the function to renamed_name, and when calling, call the corresponding module/module function through renamed_name;


2. Code example - import import module to set alias


Code example:

"""
异常传递 代码示例
"""
# 导入时间模块
import time as t

print("开始执行")

# 使用时间模块的 sleep 休眠功能
t.sleep(3)

print("结束执行")

Results of the :
insert image description here


3. Code example - from import module setting alias


Code example:

"""
异常传递 代码示例
"""
# 导入时间模块
from time import sleep as s

print("开始执行")

# 使用时间模块的 sleep 休眠功能
s(3)

print("结束执行")

Results of the :

insert image description here

Guess you like

Origin blog.csdn.net/han1202012/article/details/131394104