AttributeError: 'module' 对象没有属性 [英] AttributeError: 'module' object has no attribute

查看:53
本文介绍了AttributeError: 'module' 对象没有属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个 python 模块:

I have two python modules:

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 时,我得到:

When I run a.py, I get:

AttributeError: 'module' object has no attribute 'hi'

错误是什么意思?我该如何解决?

What does the error mean? How do I fix it?

推荐答案

你有相互的顶级导入,这几乎总是一个坏主意.

You have mutual top-level imports, which is almost always a bad idea.

如果你真的必须在 Python 中进行相互导入,那么这样做的方法是在一个函数中导​​入它们:

If you really must have mutual imports in Python, the way to do it is to import them within a function:

# In b.py:
def cause_a_to_do_something():
    import a
    a.do_something()

现在 a.py 可以安全地执行 import b 而不会引起问题.

Now a.py can safely do import b without causing problems.

(乍一看,cause_a_to_do_something() 可能会非常低效,因为每次调用它时它都会执行 import,但实际上导入只工作第一次就搞定了.第二次和以后导入一个模块,这是一个快速的操作.)

(At first glance it might appear that cause_a_to_do_something() would be hugely inefficient because it does an import every time you call it, but in fact the import work only gets done the first time. The second and subsequent times you import a module, it's a quick operation.)

这篇关于AttributeError: 'module' 对象没有属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆