如何“测试"无在python中输入? [英] How to "test" NoneType in python?
问题描述
我有一个有时会返回 NoneType 值的方法.那么我如何质疑一个 NoneType 的变量呢?我需要使用 if 方法,例如
I have a method that sometimes returns a NoneType value. So how can I question a variable that is a NoneType? I need to use if method, for example
if not new:
new = '#'
我知道这是错误的方式,我希望你明白我的意思.
I know that is the wrong way and I hope you understand what I meant.
推荐答案
那么我如何质疑一个 NoneType 的变量?
So how can I question a variable that is a NoneType?
使用is
操作符,像这样
if variable is None:
为什么会这样?
因为 None
是 NoneType
在 Python 中,我们可以使用 iscode> 运算符,用于检查变量中是否包含
None
.
Since None
is the sole singleton object of NoneType
in Python, we can use is
operator to check if a variable has None
in it or not.
引用自 is
文档,
Quoting from is
docs,
运算符 is
和 isnot
测试对象身份:x is y
为真当且仅当 x
和 y
是同一个对象.x is not y
产生反真值.
The operators
is
andis not
test for object identity:x is y
is true if and only ifx
andy
are the same object.x is not y
yields the inverse truth value.
由于 None
只能有一个实例,is
将是检查 None
的首选方式.
Since there can be only one instance of None
, is
would be the preferred way to check None
.
从马嘴里听出来
引用 Python 的编码风格指南 - PEP-008(由 Guido 共同定义)自己),
Quoting Python's Coding Style Guidelines - PEP-008 (jointly defined by Guido himself),
与 None
之类的单例相比,应该始终使用 is
或 is not
,从不等式运算符.
Comparisons to singletons like
None
should always be done withis
oris not
, never the equality operators.
这篇关于如何“测试"无在python中输入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!