问题描述
我可能遗漏了一些明显的东西,但无论如何:
当您在 python 中导入像 os
这样的包时,您可以立即使用任何子模块/子包.例如这有效:
但是我有自己的包,其结构如下:
FooPackage/__init__.py文件
这里同样的逻辑不起作用:
>>>导入 FooPackage>>>FooPackage.fooAttributeError: 'module' 对象没有属性 'foo'我做错了什么?
需要导入子模块:
import FooPackage.foo
你正在做的是在 FooPackage/__init__.py
中寻找 foo
.您可以通过将 import FooPackage.foo as foo
(或 from .import foo
)放在 FooPackage/__init__.py
中来解决它,然后 Python 会能够在那里找到 foo
.但我建议使用我的第一个建议.
I am probably missing something obvious but anyway:
When you import a package like os
in python, you can use any submodules/subpackages off the bat. For example this works:
>>> import os
>>> os.path.abspath(...)
However I have my own package which is structured as follows:
FooPackage/
__init__.py
foo.py
and here the same logic does not work:
>>> import FooPackage
>>> FooPackage.foo
AttributeError: 'module' object has no attribute 'foo'
What am I doing wrong?
You need to import the submodule:
import FooPackage.foo
What you're doing is looking for foo
in FooPackage/__init__.py
. You could solve it by putting import FooPackage.foo as foo
(or from . import foo
) in FooPackage/__init__.py
, then Python will be able to find foo
there. But I recommend using my first suggestion.
这篇关于在 Python 中导入包的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!