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
:
foo.bar
打印 The module "bar" prints "bar"
foo.bar.print_message()
打印 The function print_message() prints this 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 . 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
在当前工作目录中:
包 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
:
foo.bar
打印The module "bar" prints "bar"
foo.bar.print_message()
打印The function print_message() prints this 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 . 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