我正在运行一些python3代码,这些代码偶尔会得到一个列表、dict和None。
fieldType = type(raw_data[root_key].get("oslc_cm:ChangeRequest"))
print('fieldType=')
print(fieldType)
if fieldType is None:
print('its none')
else:
print('its not none')这适用于所有方面,但当fieldType为“None”时除外:
fieldType=
<class 'collections.OrderedDict'>
its not none
#this output works as expected但是,当fieldType是<class 'NoneType'>时,它报告说它是“没有”
fieldType=
<class 'NoneType'>
its not none为什么我的代码不能正确识别什么时候一个对象是'None‘类型的?
发布于 2022-03-09 22:15:22
fieldType是<class 'NoneType'>,这与None不同。它永远不可能是None,因为type总是返回某种类型。
看来你想
raw_data[root_key].get("oslc_cm:ChangeRequest") is None而不是
fieldType is None发布于 2022-03-09 22:16:20
None != type(None)
type(None)是一个<class 'type'>对象。使用isinstance()是python中一种变量类型切赫的正确方法。那么您的代码将如下所示:
NoneType = type(None)
fieldType = type(raw_data[root_key].get("oslc_cm:ChangeRequest"))
print('fieldType=')
print(fieldType)
if isinstance(fieldType, NoneType):
print('its none')
else:
print('its not none')发布于 2022-03-09 22:13:45
这是一个常见的错误。测试值为None的正确方法是使用是或不是,而不是使用相等测试:
if fieldType is None:
print('its none')
else:
print('its not none')当字典中没有项时,get()方法返回None (因此计算为False)。这意味着您将通过使用if not raw_data[root_key].get("oslc_cm:ChangeRequest")获得相同的结果:这意味着“如果没有oslc_cm:ChangeRequest in raw_data[root_key]条目”。因此,您可以这样编写代码:
fieldType = type(raw_data[root_key].get("oslc_cm:ChangeRequest"))
if fieldType is not None:
print('its not none')
else:
print('its none')https://stackoverflow.com/questions/71416542
复制相似问题