我有两个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。
其他回答
导入的顺序是我遇到问题的原因:
a.py:
############
# this is a problem
# move this to below
#############
from b import NewThing
class ProblemThing(object):
pass
class A(object):
###############
# add it here
# from b import NewThing
###############
nt = NewThing()
pass
b.py:
from a import ProblemThing
class NewThing(ProblemThing):
pass
这只是另一个例子,类似于richieindie的答案,但是有类。
我通过引用一个以错误方式导入的enum得到了这个错误,例如:
from package import MyEnumClass
# ...
# in some method:
return MyEnumClass.Member
正确的导入:
from package.MyEnumClass import MyEnumClass
希望这能帮助到别人
解决了
Python正在你的a.py模块中寻找a对象。
将该文件重命名为其他文件或使用
from __future__ import absolute_import
在a.py模块的顶部。
我遇到这个错误是因为实际上没有导入模块。代码是这样的:
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。
以上所有的答案都很棒,但我想在这里插一句。如果你没有发现上面提到的任何问题,试着清理一下你的工作环境。这对我很管用。