use*_*679 2 python python-3.x nonetype
我知道不建议比较类型,但我有一些代码在if elif系列中执行此操作.但是,我对于None值如何工作感到困惑.
def foo(object)
otype = type(object)
#if otype is None: # this doesn't work
if object is None: # this works fine
print("yep")
elif otype is int:
elif ...
Run Code Online (Sandbox Code Playgroud)
为什么我可以比较is int好等等,但没有is None?types.NoneType似乎在Python 3.2中消失了,所以我无法使用它......
下列
i = 1
print(i)
print(type(i))
print(i is None)
print(type(i) is int)
Run Code Online (Sandbox Code Playgroud)
版画
1
<class 'int'>
False
True
Run Code Online (Sandbox Code Playgroud)
而
i = None
print(i)
print(type(i))
print(i is None)
print(type(i) is None)
Run Code Online (Sandbox Code Playgroud)
版画
None
<class 'NoneType'>
True
False
Run Code Online (Sandbox Code Playgroud)
我觉得None很特别,但是给出了什么?是否NoneType真的存在,或Python的骗我?
你永远不需要比较NoneType,因为None是一个单身人士.如果你有一些obj可能的对象,那None就是obj is None或obj is not None.
你的比较不起作用的原因是它None不是一个类型,它是一个值.它类似于尝试type(1) is 1整数示例.如果你真的想做一个NoneType检查,你可以使用type(obj) is type(None),或者更好isinstance(obj, type(None)).
None是Python提供的特例单例. NoneType是单例对象的类型. type(i) is None是的False,但type(i) is type(None)应该是真的.
| 归档时间: |
|
| 查看次数: |
4366 次 |
| 最近记录: |