我有两个 python 模块:
一个.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 可以安全地执行
import b
不会引起问题。(乍一看,
cause_a_to_do_something()
可能会非常低效,因为它每次调用它时都会执行 import
,但实际上导入工作只在第一次完成。第二次和后续导入模块,这是一个快速的操作。)
关于python - AttributeError: 'module' 对象没有属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44488045/