AttributeError: 'NoneType' object has no attribute 'get' while on loop

AttributeError: 'NoneType' object has no attribute 'get' while on loop

我知道这是一个属性错误,是由于试图访问

上未定义的 属性 而引起的

所以基本上我正在解析 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

但是当在 class 函数中访问相同的内容时,它会引发属性错误。我做错了什么?

仅当 someProperty 的值为 null 时以编程方式调用方法时才会引发错误。

更新

这就是我在 class.

中使用的方式
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()

您忘记了 someProperty 存在但设置为 None 的情况。您在输入中包含了该案例 JSON:

{
    "someProperty":null
}

此处存在键 ,其值设置为 None(Python 相当于 [=35= 中的 null ]).然后 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() 只有 returns 键不存在时的默认值。在上面的示例中,"someProperty" 存在,因此返回它的值。

我会用空字典替换任何虚假值:

# value could be None, or key could be missing; replace both with {}
property = kwargs.get('someProperty') or {}  
self.value = property.pop('value', 0)