python中none是什么类型_如何在Python中”测试”None类型?

我有一个方法,它有时返回一个非类型的值。那么我怎样才能质疑一个非类型的变量呢?例如,我需要使用if方法

if not new:

new = '#'

我知道这是错误的方式,我希望你理解我的意思。

我想这是在这里回答的,显然是在以前的某个地方。

如果您的方法返回的值只有bool(returnValue)等于False,那么if not new:应该可以正常工作。这有时发生在内置libs中——例如,re.match返回none或truthy match对象。

也可以在这里看到我关于python中的null和None的答案。

So how can I question a variable that is a NoneType?

使用is运算符,如下所示

if variable is None:

为什么会这样?

由于None是python中NoneType唯一的单例对象,所以我们可以使用is操作符来检查变量中是否有None。

引用is号文件,

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的首选方法。

从马嘴里听到

引用了python的编码风格指南-pep-008(由guido自己共同定义)。

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

if variable is None:

...

if variable is not None:

...

根据亚历克斯·霍尔的回答,也可以用isinstance来完成:

>>> NoneType = type(None)

>>> x = None

>>> type(x) == NoneType

True

>>> isinstance(x, NoneType)

True

isinstance也是直观的,但其复杂之处在于,它需要一条线。

NoneType = type(None)

这对于像int和float这样的类型是不需要的。

由于你不能将NoneType分为子类,由于None是单体,因此不应使用isinstance来检测None,而应按照公认的答案进行,并使用is None或is not None。

不在python3.6.7上工作

正如亚伦希尔的命令所指出的:

Since you can't subclass NoneType and since None is a singleton, isinstance should not be used to detect None - instead you should do as the accepted answer says, and use is None or is not None.

原始答案:

然而,最简单的方法是,除了豆蔻的答案之外,如果没有额外的行,可能是:isinstance(x, type(None))

So how can I question a variable that is a NoneType? I need to use if method

使用isinstance()不需要if语句中的is:

if isinstance(x, type(None)):

#do stuff

附加信息您还可以在一个isinstance()语句中检查多个类型,如文档中所述。只需将类型编写为元组即可。

isinstance(x, (type(None), bytes))

由于你不能将NoneType分为子类,由于None是单体,因此不应使用isinstance来检测None,而应按照公认的答案进行,并使用is None或is not None。

这个答案对python 3.6.7很有用。

Python 2.7:

x = None

isinstance(x, type(None))

isinstance(None, type(None))

=真

由于你不能将NoneType分为子类,由于None是单体,因此不应使用isinstance来检测None,而应按照公认的答案进行,并使用is None或is not None。

哦,好吧!谢谢!

希望这个例子对您有所帮助)

print(type(None) # NoneType

所以,您可以检查变量名的类型

#Example

name = 12 # name = None

if type(name) != type(None):

print(name)

else:

print("Can't find name")

不确定这是否回答了问题。但我知道我花了一段时间才弄明白。我在浏览一个网站,突然作者的名字不在了。所以需要一个支票声明。

if type(author) == type(None):

my if body

else:

my else body

在这种情况下,author可以是任何变量,None可以是您要检查的任何类型。

由于None是单体的,所以不应使用type来检测None—而是应按照公认的答案进行,并使用is None或is not None。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值