在当前工作目录中:
该软件包foo包含模块bar.py和一个空__init__.py文件。
为了论证,该模块bar.py包含以下代码:
def print_message():
print 'The function print_message() prints this message'
print 'The module \"bar\" prints \"bar\"'
Run Code Online (Sandbox Code Playgroud)
预期的行为时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())
到目前为止,我浏览过的关于SO的所有评分最高的问题AttributeError,都针对与模块中某些内容有关的答案,而不是与导入本身有关。此外,每次尝试之间都会重新启动内核。
问题:并不是一个阻碍点,但是它使我烦恼,无法理解这种行为。我比较没有经验,所以我在这里缺少什么基本概念?谢谢,