null object in Python?
我如何引用Python中的空对象?
In Python, the 'null' object is the singleton None
.
The best way to check things for "Noneness" is to use the identity operator, is
:
if foo is None:
...
It's not called null as in other languages, but None
. There is always only one instance of this object, so you can check for equivalence with x is None
(identity comparison) instead of x == None
, if you want.
In Python, to represent the absence of a value, you can use the None value (types.NoneType.None) for objects and "" (or len() == 0) for strings. Therefore:
if yourObject is None: # if yourObject == None:
...
if yourString == "": # if yourString.len() == 0:
...
Regarding the difference between "==" and "is", testing for object identity using "==" should be sufficient. However, since the operation "is" is defined as the object identity operation, it is probably more correct to use it, rather than "==". Not sure if there is even a speed difference.
Anyway, you can have a look at:
上一篇: JavaScript中的null和undefined有什么区别?
下一篇: Python中的空对象?