我有两个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中有相互导入,方法是在函数中导入它们:
# In b.py:
def cause_a_to_do_something():
import a
a.do_something()
现在a.py可以安全地导入b而不会产生问题。
(乍一看,cause_a_to_do_something()似乎效率非常低,因为每次调用它时它都会导入,但实际上导入工作只在第一次执行。第二次和以后导入一个模块时,这是一个快速操作。)
在某些情况下,可能只是文件保存在正确的目录中,但在虚拟环境中写入文件时,文件中写入的python还没有保存。因此,当python将a.py导入到b.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。
在ubuntu 18.04 (virtualenv, python.3.6.x)上,下面的重载代码段为我解决了这个问题:
main.py
import my_module # my_module.py
from importlib import reload # reload
reload(my_module)
print(my_module)
print(my_modeule.hello())
地点:
|--main.py
|--my_module.py
查看更多文档:这里