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.)
这篇好文章是转载于:学新通技术网
- 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
- 本站站名: 学新通技术网
- 本文地址: /reply/detail/tanhcffgag
-
YouTube API 不能在 iOS (iPhone/iPad) 工作,但在桌面浏览器工作正常?
it1352 07-30 -
iPhone,一张图像叠加到另一张图像上以创建要保存的新图像?(水印)
it1352 07-17 -
保持在后台运行的 iPhone 应用程序完全可操作
it1352 07-25 -
使用 iPhone 进行移动设备管理
it1352 07-23 -
在android同时打开手电筒和前置摄像头
it1352 09-28 -
检查邮件是否发送成功
it1352 07-25 -
扫描 NFC 标签时是否可以启动应用程序?
it1352 08-02 -
Android微调工具-删除当前选择
it1352 06-20 -
Android App 和三星 Galaxy S4 不兼容
it1352 07-20 -
希伯来语的空格句子标记化错误
it1352 06-22