python - AttributeError: 'module' 对象没有属性 'xxxx'

标签 python module package attributeerror

在当前工作目录中:

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 打印 模块“bar”打印“bar”
  2. foo.bar.print_message() 打印 函数 print_message() 打印此消息

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

  • 一方面,使用 from foo import bar 然后允许调用 bar.print_message()

  • 另一方面,如果我import foo,那么foo.bar会产生 标题错误:AttributeError: 'module' object has no attribute 'bar'(foo.bar.print_message() 也是如此)

到目前为止,我浏览过的关于 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 。将 bar 导入 init.py 文件。这将使 foo 在导入时运行 init.py 文件时知道 bar。 https://docs.python.org/3/tutorial/modules.html有一些关于模块和包的信息,这篇文章中有一些非常好的信息 Importing packages in Python

关于python - AttributeError: 'module' 对象没有属性 'xxxx',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47323411/

相关文章:

python - 为什么比较空值不起作用?

Python:模块和打包 - 为什么 __init__.py 文件不在 __main__.py 之前执行?

javascript - 简化 `import as`语法

linux - 无法找到 RHEL 8 的 libnl RPM 软件包?

python - 请求响应的 Xpath 返回空列表

python - 迭代特定范围的索引和算法伪代码-> python

python - 无效请求状态 : oauth2 flask

performance - Fortran 模块性能

java - 如何让 jfreechart 在 Eclipse 中工作 (Windows 7)

java - 包P1和P2有依赖循环,但是P1的类没有使用P2(通过jdepend分析)