![54f78fb072bcdf95f9e03622103b174a.gif](https://img-blog.csdnimg.cn/img_convert/54f78fb072bcdf95f9e03622103b174a.gif)
如何导入包
![e75b53188273bc9768795144b76f0d45.png](https://img-blog.csdnimg.cn/img_convert/e75b53188273bc9768795144b76f0d45.png)
如何导入一个包(package),其实所谓的导入一个包,其实是导入包下的_init_.py文件
一个包下有test1.py模块,上级目录中的p.py模块,如何实现通过p.py去调用_init_.py下的内容?
![9880611fc83df1ca6944152d5d0ae9d5.png](https://img-blog.csdnimg.cn/img_convert/9880611fc83df1ca6944152d5d0ae9d5.png)
test1.py下的内容如下:
def test(): print('in the test1')
![f6e45f422e6ee776fd343be59ab89973.png](https://img-blog.csdnimg.cn/img_convert/f6e45f422e6ee776fd343be59ab89973.png)
_init_.py下的内容:
from . import test1
![5c36019180c74d3cb54a8fb3bf63e82e.png](https://img-blog.csdnimg.cn/img_convert/5c36019180c74d3cb54a8fb3bf63e82e.png)
p.py下的内容:
import package--->导入package下的_init_.py中的内容。
![6d5bc91e977c54c2568f3ff0aea45a7a.png](https://img-blog.csdnimg.cn/img_convert/6d5bc91e977c54c2568f3ff0aea45a7a.png)
整个调用过程就是:
p.py下导入包-->包下的_init_.py又调用了test1-->test1中的内容定义了test函数。
p.py执行时package.test1.test()。
要想导入某一个包下的一堆模块,首先要修改包文件_init_.py下通过相对路径from . import test1导入
就相当于把test1下的所有代码搬到当前路径下
![957349d061678945645b43712d94ef74.png](https://img-blog.csdnimg.cn/img_convert/957349d061678945645b43712d94ef74.png)
导入优化
![3067464c38b7ee82d3a016919683c027.png](https://img-blog.csdnimg.cn/img_convert/3067464c38b7ee82d3a016919683c027.png)
新创建一个目录,test4,test4下包含两个文件(module_test.py、test.py)
![2b9ba9335d206745416e06357f24cbb4.png](https://img-blog.csdnimg.cn/img_convert/2b9ba9335d206745416e06357f24cbb4.png)
module_test.py的内容:
def test(): print('in the module')
test.py的内容:
import module_testdef logger(): module_test.test() print('in the logger')def search(): module_test.test() print('in the search')
假如module_test.py下的test函数在test.py下被多次重复调用,此时可使用from module_test import test,而不能使用import module_test的方式,这样做的优点就是,可以直接省去去重复查找的过程,而使用from方式,可直接进行调用。
优化后的代码如下:
from module_test import testdef logger(): test() print('in the logger')def search(): test() print('in the search')
结语
感谢阅读,欢迎在评论区中发表自己不同的观点,若有其他问题请在评论区留言,喜欢的朋友请多多关注转发支持一下。
![656ae829e8e46c775ce4e9cf87ea5a82.gif](https://img-blog.csdnimg.cn/img_convert/656ae829e8e46c775ce4e9cf87ea5a82.gif)