栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

if object vs if object is None

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

if object vs if object is None

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,也为空。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/295989.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号