如何“测试"无在python中输入? [英] How to "test" NoneType in python?

查看:47
本文介绍了如何“测试"无在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:

为什么会这样?

因为 NoneNoneType 在 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,

运算符 isisnot 测试对象身份:x is y 为真当且仅当 xy 是同一个对象.x is not y 产生反真值.

The operators is and is not test for object identity: x is y is true if and only if x and y 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 之类的单例相比,应该始终使用 isis not从不等式运算符.

Comparisons to singletons like None should always be done with is or is not, never the equality operators.

这篇关于如何“测试"无在python中输入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆