python3使用相对路径导包出现ImportError: cannot import name ‘xxx‘
目录结构如下:init.py 内容print('init->begin')config = "config"#由于info的关系,此处的导包需放在config = "config"之后from . import infoprint('init->end')__all__ = ['config', 'info', 'other']info.py 内容from ...
目录结构如下:
__init__.py
内容
print('init->begin')
config = "config"
# 由于info的关系,此处的导包需放在config = "config"之后
from . import info
print('init->end')
__all__ = ['config', 'info', 'other']
info.py
内容
from . import config
info_1 = 'from info'
print(info_1)
print(config)
other.py
内容
from . import config
other_1 = 'from other'
print(other_1)
print(config)
在其他地方模块中进行from my_test import *
导入, 直接运行的结果显示如下:
init->begin
from info
config
init->end
from other
config
若__init__.py中修改__all__ = ['config', 'info']
, 运行结果如下:
init->begin
from info
config
init->end
因为__all__中指明的是包中对外提供的属性,不指明的话,在使用*
被导入的时候,不会被导入, 但可以被直接导入【eg:from my_test import other
】这样的话,运行结果和第一次一样!
此外注意:
在python3中,使用相对路径导包一定要注意,举例还是以上的目录结构, 如果直接运行info.py
或者other.py
会报错:
ImportError: cannot import name 'config'
此种情况,在启动文件中导包要谨慎使用相对路径.
应该直接使用绝对路径from my_test import config进行导包, 请看修改后内容:
运行结果如下【注意观察,会发现,红色框内重复打印】:
原因是python中的包(包的特征就是一定要有__init__py
文件,即使__init__.py
为空)被导入时,会执行__init__.py
文件,所以控制栏中第一次打印出from info 和 config
是__init__.py
加载完info.py
并执行的结果,第二次打印出的from info 和 config
才是info.py
自己运行的结果
【PS】:希望能够帮助有困惑的童鞋,写的比较匆忙,如有错误,欢迎指正,谢谢~
更多推荐
所有评论(0)