我有一个方法,有时返回一个NoneType值。因此,我如何质疑一个变量是一个NoneType?例如,我需要使用if方法
if not new:
new = '#'
我知道这是错误的方式,我希望你能理解我的意思。
我有一个方法,有时返回一个NoneType值。因此,我如何质疑一个变量是一个NoneType?例如,我需要使用if方法
if not new:
new = '#'
我知道这是错误的方式,我希望你能理解我的意思。
当前回答
if variable is None:
...
if variable is not None:
...
其他回答
根据Alex Hall的回答,也可以用isinstance来实现:
>>> NoneType = type(None)
>>> x = None
>>> type(x) == NoneType
True
>>> isinstance(x, NoneType)
True
Isinstance也是直观的,但有一个复杂的问题,它需要行
NoneType =类型(无)
这对于int和float类型不需要。
我希望这个例子对你有帮助)
print(type(None)) # NoneType
你可以检查变量名的类型
# Example
name = 12 # name = None
if type(name) is type(None):
print("Can't find name")
else:
print(name)
我主要使用以下方法来检查NoneType。
if (new): # not None
...
else: # NoneType
...
if variable is None:
...
if variable is not None:
...
不确定这是否回答了问题。但我知道我花了一段时间才想明白。我在循环浏览一个网站,突然作者的名字不在了。所以需要一个检查语句。
if type(author) == type(None):
print("my if body")
else:
print(" my else body")
在这种情况下,Author可以是任何变量,None可以是您正在检查的任何类型。