对不少 Python 初学者来说,Python 导入其他模块的方式让他们很难理解。什么时候用import xxx
?什么时候用from xxx import yyy
?什么时候用from xxx.yyy import zzz
?什么时候用from xxx import *
?
这篇文章,我们来彻底搞懂这个问题。
系统自带的模块
以正则表达式模块为例,我们经常这样写代码:
import re
target = 'abc1234xyz'
re.search('(\d+)', target)
但有时候,你可能会看到某些人这样写代码:
from re import search
target = 'abc1234xyz'
search('(\d+)', target)
那么这两种导入方式有什么区别呢?
我们分别使用type
函数来看看他们的类型:
>>> import re
>>> type(re)
<class 'module'>
>>> from re import search
>>> type(search)
<class 'function'>
如下图所示:
![9e2ef248ecaece034e0c50d9a00e521a.png](https://i-blog.csdnimg.cn/blog_migrate/baa5b380491a9cd5887b65881808733c.png)
可以看到,直接使用import re
导入的re
它是一个module
类,也就是模块。我们把它成为正则表达式模块
。而当我们from re import search
时,这个search
是一个function
类,我们称呼它为search 函数
。
一个模块里面可以包含多个函数。
如果在你的代码里面,你已经确定只使用search
函数,不会再使用正则表达式里面的其他函数了,