Skip to main content
 首页 » 编程设计

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

2025年05月04日21youxin

在当前工作目录中:

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