
01
引言
虽然大家都十分熟悉Python中的import函数,它是Python中导入模块的内置函数,可以用来动态导入模块。本文将深入讨论关于Python中导入机制的几个有趣且深入的知识点
02
__import__
import pandas as pddf = pd.DataFrame()
pd = __import__('pandas')df = pd.DataFrame()
03
__all__
这里假设我们有两个文件 a.py 和 b.py。
# a.pyfrom b import *
# b.pydef test1():passdef test2():passdef test3():pass
此时,由于有from b import *语句,a.py会从b.py中导入所有内容。但是,如果我们在b.py中添加 __all__ ,情况可能会有所改变
# a.pyfrom b import *
# b.pydef test1():passdef test2():passdef test3():pass__all__ = ['test1', 'test2']
在这里,__all__列表定义了在使用from b import *语句时从 b.py 导入的内容。在本例中,只有test1和test2会从b.py导入,而test3没有被指定,则不会被导入。
04
absolute imports
比方说,我们有一个 hello.py 嵌套在一堆文件夹的深处:
test1|-test2|-test3hello.pya.py
其中,hello.py 的内容:
def hello():print('hello')
现在,假设我们正在使用 a.py,并希望从hello.py导入 hello 函数。为此,我们可以使用绝对导入。如下所示:
# a.pyfrom test1.test2.test3.hello import hellohello()# hello
05
假设同一文件夹中有两个文件,a.py 和 b.py ,如下
# a.pyfrom b import *if __name__ == '__main__':print('only runs when i run a.py directly')
# b.pydef hello_from_b():print('hello from b.py')if __name__ == '__main__':print('only runs when i run b.py directly')
当运行pthon a.py时,我们的输出为only runs when i run a.py directly。
除非大家明确运行b.py,否则b.py中的 if__name__ == '__main__' 中的任何内容都不会运行。这对于防止意外运行我们不想运行的代码非常有用。
这是因为当我们直接运行Python脚本a.py时,此时只有a.py中的__name__ 等于"__main__"。
06
假设我们有 3 个文件,
test|- b.py|- c.pya.py
导入规则如下:
-
a.py 从 b.py 导入 b.py 从 c.py 导入
# c.pydef hello_from_c():print('hello')
# b.pyfrom .c import hello_from_c
# a.pyfrom test.b import hello_from_chello_from_c()# hello
这里,语句 from .c import hello_from_c 是相对导入。前面的 . 表示和 c.py 在同一目录下。如果我们的绝对路径很长,而我们又不想全部键入,那么这个功能就很有用。
07
到目前为止,我们已经介绍了 Python中导入模块的常用用法。希望大家也可以从这篇文章中获得一些关于导入机制的有用知识。
您学废了嘛?
点击上方小卡片关注我
扫码进群,交个朋友!


