• 首页 首页 icon
  • 工具库 工具库 icon
    • IP查询 IP查询 icon
  • 内容库 内容库 icon
    • 快讯库 快讯库 icon
    • 精品库 精品库 icon
    • 问答库 问答库 icon
  • 更多 更多 icon
    • 服务条款 服务条款 icon

AttributeError: 'module' 对象没有属性

用户头像
it1352
帮助1

问题说明

我有两个 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?

正确答案

#1

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

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.)

这篇好文章是转载于:学新通技术网

  • 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
  • 本站站名: 学新通技术网
  • 本文地址: /reply/detail/tanhcffgag
系列文章
更多 icon
同类精品
更多 icon
继续加载