我知道这是由于尝试访问未在
上定义的属性而导致的属性错误所以基本上我正在解析API返回的JSON响应。
响应看起来像这样。
{
"someProperty": {
"value": 123
}
},
{
"someProperty":null
},
我正在循环x = response.json()
对象并尝试访问,
x.get('someProperty', {}).pop('value', 0)
可以手动使用解释器进行测试
In[2]: x = {1:2, 2:34}
In[3]: x.get('someProperty', {}).pop('value', 0)
Out[3]: 0
但是当在类函数中访问它时,它会引发属性错误。我做错了什么?
只有在someProperty
的值为空时以预定方式调用方法时才会引发错误。
这就是我在课堂上使用的方式。
class SomeClass(object):
def __init__(self, **kwargs):
self.value = kwargs.get('someProperty', {}).pop('value', 0)
def save():
pass
现在用法,
x = response.json()
for num, i in enumerate(x):
j = SomeClass(**i)
j.save()
答案 0 :(得分:2)
您忘记了someProperty
存在的情况,但设置为None
。您在输入JSON中包含了这种情况:
{
"someProperty":null
}
此处键存在,其值设置为None
(JSON中null
的Python等价物)。然后,dict.get()
会返回该值,而None
没有.pop()
方法。
演示:
>>> import json
>>> json.loads('{"someProperty": null}')
{'someProperty': None}
>>> x = json.loads('{"someProperty": null}')
>>> print(x.get("someProperty", 'default ignored, there is a value!'))
None
如果密钥不存在, dict.get()
仅返回默认值。在上面的示例中,"someProperty"
存在,因此会返回它的值。
我用空字典替换任何falsey值:
# value could be None, or key could be missing; replace both with {}
property = kwargs.get('someProperty') or {}
self.value = property.pop('value', 0)