我有两个python模块:
a.py
import b
def hello():
print "hello"
print "a.py"
print hello()
print b.hi()
b.py
import a
def hi():
print "hi"
当我运行a.py时,我得到:
AttributeError: 'module' object has no attribute 'hi'
这个误差是什么意思?我该怎么解决呢?
我有两个python模块:
a.py
import b
def hello():
print "hello"
print "a.py"
print hello()
print b.hi()
b.py
import a
def hi():
print "hi"
当我运行a.py时,我得到:
AttributeError: 'module' object has no attribute 'hi'
这个误差是什么意思?我该怎么解决呢?
当前回答
我遇到这个错误是因为实际上没有导入模块。代码是这样的:
import a.b, a.c
# ...
something(a.b)
something(a.c)
something(a.d) # My addition, which failed.
最后一行导致一个AttributeError。原因是我没有注意到a的子模块(a.b和a.c)被显式导入,并假设import语句实际上导入了a。
其他回答
对我来说,这个错误的原因是有一个文件夹与我试图导入的python模块同名。
|-- core <-- empty directory on the same level as the module that throws the error
|-- core.py
python将该文件夹视为python包,并试图从空包“core”导入,而不是从core.py导入。
似乎出于某种原因,git在切换分支时留下了空文件夹
所以我移除了那个文件夹,一切都很顺利
你存了'b.py'吗? 你必须先保存'b.py'。
问题在于模块之间的循环依赖关系。a导入b, b导入a。但其中一个需要先加载——在这种情况下,python最终会在b之前初始化模块a,而当你试图在a中访问它时,b.hi()还不存在。
你可以通过添加2个print来理解:
a.py:
print(__name__)
import b
b.py:
print(__name__)
import a
然后:
$ python3 a.py
__main__
b
a
a.py最终会被加载/执行2次。一个作为__main__,一个作为a。
解决了
Python正在你的a.py模块中寻找a对象。
将该文件重命名为其他文件或使用
from __future__ import absolute_import
在a.py模块的顶部。