在Python中导入软件包,属性错误 [英] Importing packages in Python, attribute error
问题描述
我是Python的新手,我试图了解包和导入语句的工作方式. 我制作了这个程序包,位于我的桌面上:
I'm new in Python and I'm trying to understand how packages and import statement work. I made this package, located in my Desktop:
package/
__ init __.py
module2.py
subpackage1/
__ init __.py
module1.py
以下是软件包文件夹__ init __ .py中的内容:
Here's what's inside __ init __ .py in the package folder:
__ all __ =["module2"]
import os
os.chdir("C:/Users/Leo--/Desktop/Package")
import subpackage1.module1
os.chdir("C:/Users/Leo--/Desktop")
并位于subpackage1文件夹的__ init __ .py中:
and inside __ init __ .py in subpackage1 folder:
__ all __ =["module1"]
我只想通过写入
import package
在解释器中输入上述命令后,我可以通过编写而毫无问题地访问module1.py的任何功能
After typing the command above into the interpreter I can access with no problems any function of module1.py by writing
package.subpackage1.module1.mod1()
其中mod1()是module1.py中定义的函数. 但是当我输入
where mod1() is a function defined in module1.py. But when I type
package.module2.mod2()
我收到"AttributeError:模块'package'没有属性'module2'"(mod2()是module2.py中定义的函数). 这是为什么? 预先谢谢你!
I get "AttributeError: module 'package' has no attribute 'module2'" (mod2() is a function defined in module2.py). Why is that? Thank you in advance!
推荐答案
之所以得到AttributeError
,是因为您没有将module2
导入到__init__.py
文件中.
You get the AttributeError
because you haven't imported the module2
in __init__.py
file.
您不应在__init__.py
中执行os.chdir()
来导入子模块.
You shouldn't do os.chdir()
in __init__.py
to import submodules.
这就是我要做的:
__ init __.py
.
from . import module2
from . import subpackage
这篇关于在Python中导入软件包,属性错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!__ init __.py
.from . import module1