我有两个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'
这个误差是什么意思?我该怎么解决呢?
当前回答
在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
查看更多文档:这里
其他回答
导入的顺序是我遇到问题的原因:
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 2.7和numpy 1.15.0版本工作的情况下,它与
pip install statsmodels=="0.10.0"
以上所有的答案都很棒,但我想在这里插一句。如果你没有发现上面提到的任何问题,试着清理一下你的工作环境。这对我很管用。
我通过引用一个以错误方式导入的enum得到了这个错误,例如:
from package import MyEnumClass
# ...
# in some method:
return MyEnumClass.Member
正确的导入:
from package.MyEnumClass import MyEnumClass
希望这能帮助到别人
你可以通过添加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。