我想做的是导入模块foo
如testPkg.foo
,不仅foo
,所以testPkg.foo.bar()
有效。
但是,当我这样做时import testPkg
,它不会导入包中的模块,而from testPkg import *
做。是否可以保留包名称 testPkg.
?
例如,该目录如下所示:
test.py
testPkg/
__init__.py
foo.py
test.py
的内容是:
import testPkg
testPkg.foo.bar()
当我执行test.py
时,它使得AttributeError
:
Traceback (most recent call last):
File "test.py", line 3, in <module>
testPkg.foo.bar()
AttributeError: 'module' object has no attribute 'foo'
__init__.py
的内容是:
__all__ = ["foo"]
foo.py
的内容是:
def bar():
print("bar")
print("foo")
最佳答案
我想我找到了答案。
__init__.py
的内容应该是这样的:
from . import foo
然后 import testPkg
将 foo
导入为 testPkg.foo
。
关于Python导入保留包名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44762955/