在python中确定变量的类型是NoneType [英] Determining a variable's type is NoneType in python

查看:72
本文介绍了在python中确定变量的类型是NoneType的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想检查一个变量是否属于 NoneType 类型.对于其他类型,我们可以执行以下操作:

 type([])==list

但是对于 NoneType 这种简单的方法是不可能的.也就是说,我们不能说type(None)==NoneType.有没有替代方法?为什么这适用于某些类型而不适用于其他类型?谢谢.

解决方案

NoneType 只是碰巧不会自动在全局范围内.这真的不是问题.

<预><代码>>>>无类型 = 类型(无)>>>x = 无>>>type(x) == NoneType真的>>>isinstance(x, NoneType)真的

无论如何,进行类型检查都是不寻常的.相反,您应该测试 x is None.

I would like to check if a variable is of the NoneType type. For other types we can do stuff like:

    type([])==list

But for NoneType this simple way is not possible. That is, we cannot say type(None)==NoneType. Is there an alternative way? And why is this possible for some types and not for others? Thank you.

解决方案

NoneType just happens to not automatically be in the global scope. This isn't really a problem.

>>> NoneType = type(None)
>>> x = None
>>> type(x) == NoneType
True
>>> isinstance(x, NoneType)
True

In any case it would be unusual to do a type check. Rather you should test x is None.

这篇关于在python中确定变量的类型是NoneType的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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