在Python中,我得到一个错误:
Exception: (<type 'exceptions.AttributeError'>,
AttributeError("'str' object has no attribute 'read'",), <traceback object at 0x1543ab8>)
给定的Python代码:
def getEntries (self, sub):
url = 'http://www.reddit.com/'
if (sub != ''):
url += 'r/' + sub
request = urllib2.Request (url +
'.json', None, {'User-Agent' : 'Reddit desktop client by /user/RobinJ1995/'})
response = urllib2.urlopen (request)
jsonofabitch = response.read ()
return json.load (jsonofabitch)['data']['children']
这个错误是什么意思,我做了什么导致了这个错误?
问题是,对于json.load
,你应该传递一个类似文件的对象,并定义一个read
函数。所以你可以使用json.load(response)
或json.load(response.read())
。
AttributeError("'str' object has no attribute 'read'",)
这正是它所说的意思:有东西试图在你给它的对象上找到一个.read
属性,而你给它的是一个str
类型的对象(即你给它一个字符串)。
错误发生在这里:
json.load (jsonofabitch)['data']['children']
好吧,你没有在任何地方寻找read
,所以它一定发生在你调用的json.load
函数中(正如完整的回溯所显示的)。这是因为json.load
试图.read
你给它的东西,但你给了它jsonofabitch
,目前它命名了一个字符串(你通过调用response
的.read
创建)。
解决方法:不要自己调用.read
;该函数会这样做,并希望你直接给它response
,以便它能这样做。
你也可以通过阅读该函数的内置 Python 文档 (尝试 help(json.load)
,或整个模块 (尝试 help(json)
),或通过检查 http://docs.python.org 上的这些函数的文档来弄清楚这个。
如果你得到一个像这样的python错误:
AttributeError: 'str' object has no attribute 'some_method'
你可能不小心用一个字符串覆盖了你的对象,从而毒害了你的对象。
如何用几行代码在python中重现这个错误:
#!/usr/bin/env python
import json
def foobar(json):
msg = json.loads(json)
foobar('{"batman": "yes"}')
运行它,它打印出:
AttributeError: 'str' object has no attribute 'loads'
但改变变量的名称,就能正常工作:
#!/usr/bin/env python
import json
def foobar(jsonstring):
msg = json.loads(jsonstring)
foobar('{"batman": "yes"}')
这个错误是由于你试图在一个字符串中运行一个方法造成的。 字符串有一些方法,但不是你正在调用的那个。 所以不要再试图调用一个String没有定义的方法,而是开始寻找你的对象在哪里中毒了。