无对象返回缺失

2024-04-25 10:30:00 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个我正在创建的对象,有时它不会被创建,即None。你知道吗

我执行以下操作 dic.get("findThis")但由于dic有时是None,它将返回AttributeError: 'NoneType' object has no attribute 'get'

有一些解决方案,比如使用

if not dic: 
  print "MISSING" 
else: 
  #do your stuff`. 

有什么更好的办法?你知道吗


Tags: 对象nononegetifobjectnotattribute
2条回答

你在找三元运算符吗?你知道吗

result = dic.get("findThis") if dic else None

你可以用defaultdict这样使用它:

import collections

#example function returning the dict
def get_dict_from_json_response():
    return {'findThis2':'FOUND!'}

defdic = collections.defaultdict(lambda: 'MISSING')

#get your dict
dic = get_dict_from_json_response()

if dic:
   defdic.update(dic) #copy values

dic = defdic #now use defaultdict
print [dic["findThis"],dic["findThis2"],dic["findThis3"],dic["findThis4"],dic["findThis5"],dic["findThis6"]]

输出:

['MISSING', 'FOUND!', 'MISSING', 'MISSING', 'MISSING', 'MISSING']

相关问题 更多 >