我有两个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'
这个误差是什么意思?我该怎么解决呢?
当前回答
导入的顺序是我遇到问题的原因:
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的答案,但是有类。
其他回答
当我从git中签出一个旧版本的存储库时,我遇到了这个问题。Git替换了我的.py文件,但留下了未跟踪的.pyc文件。由于.py文件和.pyc文件不同步,.py文件中的导入命令无法在.pyc文件中找到相应的模块。
解决方案就是删除.pyc文件,并让它们自动重新生成。
循环导入会导致问题,但Python有内置的方法来缓解它。
问题是,当你运行python a.py时,它运行a.py,但没有将其标记为导入模块。因此依次a.py ->导入模块b ->导入模块a ->导入模块b。最后一次导入是无操作的,因为b目前正在导入,Python会防止这种情况发生。b现在是一个空模块。所以当它执行b.hi()时,它找不到任何东西。
注意,执行的b.hi()是在a.py ->模块b ->模块a期间,而不是直接在a.py中。
在你的特定示例中,你可以在顶层运行python -c 'import a',这样a.py的第一次执行就被注册为导入模块。
在我使用python 2.7和numpy 1.15.0版本工作的情况下,它与
pip install statsmodels=="0.10.0"
对我来说,这个错误的原因是有一个文件夹与我试图导入的python模块同名。
|-- core <-- empty directory on the same level as the module that throws the error
|-- core.py
python将该文件夹视为python包,并试图从空包“core”导入,而不是从core.py导入。
似乎出于某种原因,git在切换分支时留下了空文件夹
所以我移除了那个文件夹,一切都很顺利
你可以通过添加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。