簡體   English   中英

AttributeError:“ NoneType”對象在循環時沒有屬性“ get”

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

我知道這是由於嘗試訪問未定義的屬性而導致的屬性錯誤

因此,基本上,我正在解析API返回的JSON響應。

響應看起來像這樣。

{
    "someProperty": {
         "value": 123
     }
},
{
    "someProperty":null
},

我正在循環x = response.json()對象並嘗試以as身份進行訪問,

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值為null時以編程方式調用該方法時,才會引發錯誤。

更新

這就是我在課堂上使用的方式。

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等效於JSON中的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()僅返回默認值。 在上面的示例中, "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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM