AttributeError: 'module' object has no attribute 'xxxx'

AttributeError: 'module' object has no attribute 'xxxx'

在当前工作目录中:

foo 包含模块 bar.py,以及一个空的 __init__.py 文件。

为了论证,模块 bar.py 包含以下代码:

def print_message():
    print 'The function print_message() prints this message'

print 'The module \"bar\" prints \"bar\"'

预期行为 import foo:

  1. foo.bar 打印 The module "bar" prints "bar"
  2. foo.bar.print_message() 打印 The function print_message() prints this message

相反,我努力导入 bar.py 模块:

到目前为止,我浏览过的关于 AttributeError 的所有评分最高的问题的答案都与模块中的某些内容相关,而不是导入本身。此外,内核会在每次尝试之间重新启动。

问题: 本身不是阻塞点,但不理解这种行为让我很沮丧。我相当缺乏经验,所以我在这里缺少什么基本概念? 谢谢,

当你导入 foo 时,你只是导入了包,而不是任何模块,所以当你调用 bar 时,它在 init.py 文件中查找 bar,并且该文件中没有栏。如果您不将 bar 导入模块全局命名空间,它就不知道 bar 是什么,这就是您出错的原因。

import foo
print(dir(foo)) # ['__builtins__', ...,'__spec__', 'print_message']
from foo import bar
print(dir(foo)) # ['__builtins__',..., 'bar', 'print_message']

您可以将 from . import bar 添加到 init.py 文件中。这将使 foo 在导入时运行 init.py 文件时知道 bar。 https://docs.python.org/3/tutorial/modules.html has some information about modules and packages, and there's some really good info in this post here Importing packages in Python