在 Python 3 中导入模块时出现 AttributeError [英] AttributeError when importing modules in Python 3

查看:61
本文介绍了在 Python 3 中导入模块时出现 AttributeError的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写一个使用 json 和 requests 模块的脚本.在我编写脚本之前,我在交互式 shell 上玩弄命令,自从为我的代码创建了一个实际文件后,一切都以某种方式被破坏了.我第一次运行代码时,文件夹中出现了一个 pycache 文件夹,我认为这以某种方式破坏了一切.该代码在 shell 中逐行运行时,不再适用于此 pycache 文件夹的存在.我的代码如下:

I am trying to write a script that makes use of the json and requests modules. Before I wrote the script, I was playing around with commands on the interactive shell, and since creating an actual file for my code, everything has somehow broken. The first time I ran the code, a pycache folder appeared in the folder and I think that is somehow breaking everthing. The code, when run line by line in the shell, no longer works either with the presence of this pycache folder. My code is as follows:

import json
import requests
r = requests.get('http://api.wunderground.com/api/78c2f37e6d924b1b/hourly/q/CA/Berkeley.json')
data = json.loads(r.text)
for x in range(0, 35):
    print(data['hourly_forecast'][x]['FCTTIME']['hour'])

这应该会打印出天气预报中的所有小时数,但是我得到一个AttributeError: 'module' object has no attribute 'dumps'.在这个文件夹中,我之前还有另一个使用外部模块的程序,也没有长期使用 pycache 文件夹的存在,所以我几乎可以肯定它是导致问题的原因.但是,删除它并不能解决任何问题,因为代码仍然不起作用,它只是被重新创建.

This should print out all the hours in the weather forecast, but I get an "AttributeError: 'module' object has no attribute 'dumps'. In this folder, I also previously had another program that used external modules that also no long works with the presence of the pycache folder, so I am almost certain that it is causing the problems. However, deleting it doesn't fix anything as the code still doesn't work, and it just gets recreated.

通过删除整个错误目录并重写所有内容解决了问题.

The problem was solved by deleting the entire buggy directory and rewriting everything.

推荐答案

'module' 对象没有属性 'xxx' 的最常见原因,其中 'xxx' 是你知道''module'确实有,是这样的:你的程序所在的目录有一个'module.py',你已经忘记了修改.所以 import module 导入你的模块而不是 stdlib(或其他地方)中的预期模块.在 python-list 上发布了多个关于此问题的示例.至少有两个是由于在同一目录中被遗忘的 random.py.

The most common reason for 'module' object has no attribute 'xxx', where 'xxx' is an attribute that you 'know' 'module' does have, is this: your program is in a directory that has a 'module.py' that you have forgotten about for the modment. So import module imports your module instead of the intended module in the stdlib (or elsewhere). There have been multiple examples of this problem posted on python-list. At least two were due to a forgotten-about random.py in the same directory.

如果你发布了回溯,情况会更清楚.

The situation would have been clearer if you had posted the traceback.

这篇关于在 Python 3 中导入模块时出现 AttributeError的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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