Python代码中,判断对象是否为空,一开始很喜欢用if A,新接触的代码则发现很多人用if A is None。明明前者更简单,为什么要用后面的方式呢?
if A:
看如下注释,将调用自身的bool的方法,整个调用过程如下,先调用bool()操作,如果没有定义的bool(),则继续调用__len__() ,如果这两个方法都没有定义,则认为所有的实例为True
除了在所有空类型情况下([],{},(),’’,0 False, and None),其它的判断都会返回True
ref:https://docs.python.org/3/reference/datamodel.html#object.nonzero
object.bool(self)
Called to implement truth value testing and the built-in operation bool(); should return False or True. When this method is not defined, len() is called, if it is defined, and the object is considered true if its result is nonzero. If a class defines neither len() nor bool(), all its instances are considered true.
if A is None
只是将A与None进行比较,看是否相等,判断对象是否与None相等一定要用is 或is not而不能使用 == 或 !=
示例
def test1(para=None):
if para is None:
para = ['abc']
print(para)
def test2(para=None):
if not para:
para = ['bcd']
print(para)
if __name__ == '__main__':
test1(0)
test2(0)
test1([])
test2([])
test1()
test2()
结果:
['bcd'] ['bcd'] ['abc'] ['bcd']
不难发现 if not para 在[]和0的情况下都True,所以para为空,而在这两种情况,para并不是None;在第三种情况也就是使用默认的参数时,para才等于None,也为空。



