在python中,如何引用NoneType?

问题描述 投票:0回答:3

假设我有对象 x。 我想检查 x 是否属于我支持的类型(假设它是列表、集合、字符串和 None。并且没有从它们继承的类型),所以我想我只需检查

type(x) in (list, set, str, NoneType)

但是,NoneType 不能被引用。 有没有一个干净的解决方案,或者我必须做这样的事情?

x is None or type(x) in (list, set, str)

有标准的访问方式吗

<type 'NoneType'>

谢谢。

python
3个回答
5
投票

type(None)
怎么样?只要这样做:

type(x) in (list, set, str, type(None))

似乎对我有用,至少对我来说很清楚。由于

NoneType
只有一个值,因此将其用作文字几乎不“神奇”。


2
投票

如果您想在不调用

type()
的情况下访问它,您可以随时参考它的
__class__
,即

type(x) in (list, set, str, None.__class__)

0
投票

替代

type(None)
,从 3.10+ 开始,标准库中的 types 模块附带
NoneType
,因此,例如,要检查一个值是浮点数还是 None,您可以这样做

>>> from types import NoneType
>>> value = 12.4
>>> isinstance(value, (float, NoneType))
True
>>> value = None
>>> isinstance(value, (float, NoneType))
True

向后兼容的方法是在文件顶部定义

NoneType = type(None)

© www.soinside.com 2019 - 2024. All rights reserved.