我有两个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'
这个误差是什么意思?我该怎么解决呢?
当前回答
您有相互的顶级导入,这几乎总是一个坏主意。
如果你真的必须在Python中有相互导入,方法是在函数中导入它们:
# In b.py:
def cause_a_to_do_something():
import a
a.do_something()
现在a.py可以安全地导入b而不会产生问题。
(乍一看,cause_a_to_do_something()似乎效率非常低,因为每次调用它时它都会导入,但实际上导入工作只在第一次执行。第二次和以后导入一个模块时,这是一个快速操作。)
其他回答
问题在于模块之间的循环依赖关系。a导入b, b导入a。但其中一个需要先加载——在这种情况下,python最终会在b之前初始化模块a,而当你试图在a中访问它时,b.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的答案,但是有类。
以上所有的答案都很棒,但我想在这里插一句。如果你没有发现上面提到的任何问题,试着清理一下你的工作环境。这对我很管用。
您有相互的顶级导入,这几乎总是一个坏主意。
如果你真的必须在Python中有相互导入,方法是在函数中导入它们:
# In b.py:
def cause_a_to_do_something():
import a
a.do_something()
现在a.py可以安全地导入b而不会产生问题。
(乍一看,cause_a_to_do_something()似乎效率非常低,因为每次调用它时它都会导入,但实际上导入工作只在第一次执行。第二次和以后导入一个模块时,这是一个快速操作。)
在我使用python 2.7和numpy 1.15.0版本工作的情况下,它与
pip install statsmodels=="0.10.0"