Python导入保留包名

标签 python

我想做的是导入模块footestPkg.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 testPkgfoo 导入为 testPkg.foo

关于Python导入保留包名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44762955/

相关文章:

python - 删除重复项,但忽略空值

python - 从 Python 中的元组列表中迭代查找/替换

python - 我如何监控 Python 进程并在它死掉时重新启动?

python - 覆盖Python模块中的 "private"方法

python - tensorflow 占位符声明

python - 如何在 python 中返回字符串中的空格索引?

python - 对二维 numpy 数组的部分进行排序

python - 将 str 包含在另一行中的行分组

python - 使用 Python 图像库调整透明 png 大小和光晕效果

python - Django updateview 表单验证错误未显示在模板中