常见的5种模块导入

复制代码
 1 '''
 2 导入模块的5种方式:
 3     1. import 模块名
 4     使用import关键字导入整个模块,然后可以使用模块名加点操作符来访问模块中的函数、类或变量。例如:import math。
 5 
 6     2. from 模块名 import 功能名
 7     使用from关键字从模块中导入指定的功能(如函数、类或变量),然后可以直接使用这些功能,而不需要在代码中使用模块名进行前缀操作。例如:from math import sqrt。
 8 
 9     3. from 模块名 import *
10     使用from关键字导入模块中的所有功能,包括函数、类和变量。这种方式不需要在代码中使用模块名进行前缀操作,但可能会引入命名冲突。一般不推荐使用这种方式,除非模块中的功能确实需要全部导入。例如:from math import *。
11 
12     4. import 模块名 as 别名
13     使用import关键字导入模块,并给模块起一个别名,以简化模块名的使用。例如:import math as m,之后可以使用m.sqrt()来调用平方根函数。
14 
15     5. from 模块名 import 功能名 as 别名
16     使用from关键字导入模块中的指定功能,并给该功能起一个别名,以简化功能名的使用。例如:from math import sqrt as s,之后可以使用s()来调用平方根函数。
17 
18 需要根据具体的情况选择合适的导入方式,以保持代码的可读性和可维护性。
19 '''
20 
21 # 1. import math
22 # 导入整个math模块,可以使用math前缀来访问其中的功能
23 import math
24 
25 print(math.sqrt(16))  # 4.0
26 
27 # 2. from math import sqrt
28 # 从math模块中导入sqrt函数,直接使用该函数而无需使用模块名前缀
29 from math import sqrt
30 
31 print(sqrt(16))  # 4.0
32 
33 # 3. from math import *
34 # 导入math模块中的所有功能,包括函数、常量等。不建议使用这种方式,因为可能会引入命名冲突
35 from math import *
36 
37 print(sqrt(16))  # 4.0
38 print(pi)  # 3.141592653589793
39 
40 # 4. import math as m
41 # 导入math模块并给它起一个别名m,以简化模块名的使用。
42 import math as m
43 
44 print(m.sqrt(16))  # 4.0
45 
46 # 5. from math import sqrt as s
47 # 从math模块中导入sqrt函数,并给它起一个别名s,以简化函数名的使用。
48 from math import sqrt as s
49 
50 print(s(16))  # 4.0
复制代码

 

posted @   Allen_Hao  阅读(275)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
点击右上角即可分享
微信分享提示