我有两个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模块时遇到过这种错误。例如,我有一个名为commands的模块,它也是一个Python库模块。这被证明很难追踪,因为它在我的本地开发环境中正确工作,但在谷歌应用程序引擎上运行时失败了。

其他回答

在某些情况下,可能只是文件保存在正确的目录中,但在虚拟环境中写入文件时,文件中写入的python还没有保存。因此,当python将a.py导入到b.py时,不会导入任何代码。在其他方面是空白的。这似乎是我经常看到的一个容易识别的错误。值得一查。 科迪

我也遇到过同样的问题。 使用重载修复。

import the_module_name
from importlib import reload
reload(the_module_name)

解决了

Python正在你的a.py模块中寻找a对象。

将该文件重命名为其他文件或使用

from __future__ import absolute_import 

在a.py模块的顶部。

我通过引用一个以错误方式导入的enum得到了这个错误,例如:

from package import MyEnumClass
# ...
# in some method:
return MyEnumClass.Member

正确的导入:

from package.MyEnumClass import MyEnumClass

希望这能帮助到别人

导入的顺序是我遇到问题的原因:

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的答案,但是有类。