我有两个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导入b, b导入a。但其中一个需要先加载——在这种情况下,python最终会在b之前初始化模块a,而当你试图在a中访问它时,b.hi()还不存在。
其他回答
对我来说,这个错误的原因是有一个文件夹与我试图导入的python模块同名。
|-- core <-- empty directory on the same level as the module that throws the error
|-- core.py
python将该文件夹视为python包,并试图从空包“core”导入,而不是从core.py导入。
似乎出于某种原因,git在切换分支时留下了空文件夹
所以我移除了那个文件夹,一切都很顺利
您有相互的顶级导入,这几乎总是一个坏主意。
如果你真的必须在Python中有相互导入,方法是在函数中导入它们:
# In b.py:
def cause_a_to_do_something():
import a
a.do_something()
现在a.py可以安全地导入b而不会产生问题。
(乍一看,cause_a_to_do_something()似乎效率非常低,因为每次调用它时它都会导入,但实际上导入工作只在第一次执行。第二次和以后导入一个模块时,这是一个快速操作。)
以上所有的答案都很棒,但我想在这里插一句。如果你没有发现上面提到的任何问题,试着清理一下你的工作环境。这对我很管用。
你存了'b.py'吗? 你必须先保存'b.py'。
在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
查看更多文档:这里