AttributeError(“'str' object has no attribute 'read'”)
在Python中,我得到一个错误:
1 2 | Exception: (<type 'exceptions.AttributeError'>, AttributeError("'str' object has no attribute 'read'",), <traceback object at 0x1543ab8>) |
给定python代码:
1 2 3 4 5 6 7 8 9 10 11 | 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'] |
此错误是什么意思,我怎么做导致此错误?
问题是对于
如果收到这样的python错误:
1 | AttributeError: 'str' object has no attribute 'some_method' |
您可能通过用字符串覆盖对象意外地中毒了您的对象。
如何用几行代码在python中重现此错误:
1 2 3 4 5 6 | #!/usr/bin/env python import json def foobar(json): msg = json.loads(json) foobar('{"batman":"yes"}') |
运行它,打印:
1 | AttributeError: 'str' object has no attribute 'loads' |
但是更改变量名的名称,它可以正常工作:
1 2 3 4 5 6 | #!/usr/bin/env python import json def foobar(jsonstring): msg = json.loads(jsonstring) foobar('{"batman":"yes"}') |
当您尝试在字符串中运行方法时,导致此错误。字符串有几种方法,但您调用的不是。因此,停止尝试调用String未定义的方法,并开始寻找在何处毒害了对象。
1 | AttributeError("'str' object has no attribute 'read'",) |
这就是它的意思:某东西试图在给它的对象上找到一个
错误发生在这里:
1 | json.load (jsonofabitch)['data']['children'] |
好吧,您并没有在任何地方寻找
解决方案:不要自己打电话给
您也可以通过阅读功能的内置Python文档(尝试