我有一个函数 getPrices(),它有时返回 None,大多数时候返回字典。
当调用它时,我想在它返回 None 时传递,并在它实际返回字典时做一些事情。
我是这样处理的:
if getPrices() is None:
pass
else:
if getPrices().items():
for key, value in getPrices().items():
<do something>
现在,这显然是错误的,因为我仍然偶尔会收到此错误
if getPrices().items():
AttributeError: 'NoneType' object has no attribute 'items'
您将如何正确处理返回 None 的 getPrices() 函数?
请您参考如下方法:
这里的问题是您不断调用 getPrices(),每次它都可能返回不同的dict 或 无。
if getPrices() is None: # first call
pass
else:
if getPrices().items(): # second call
for key, value in getPrices().items(): # third call
相反,您应该存储结果值以供处理:
value = getPrices()
if value is not None:
for key, value in value.items():
# do your stuff
