if <obj> 之间的区别如果 <obj>不是无 [英] Difference between if <obj> and if <obj> is not None

查看:47
本文介绍了if <obj> 之间的区别如果 <obj>不是无的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在编写一些 XML 解析代码时,我收到了警告:

In writing some XML parsing code, I received the warning:

FutureWarning: The behavior of this method will change in future versions.  Use specific 'len(elem)' or 'elem is not None' test instead.

我使用 if : 来检查是否找到给定元素的值.

where I used if <elem>: to check if a value was found for a given element.

有人可以详细说明 if :if 之间的区别吗?不是 None: 为什么 Python 在乎我使用哪个?

Can someone elaborate on the difference between if <obj>: vs if <obj> is not None: and why Python cares which I use?

我几乎总是使用前者,因为它更短而且不是双重否定,但经常在其他人的源代码中看到后者.

I almost always use the former because it's shorter and not a double-negative, but often see the latter in other people's source code.

推荐答案

if obj is not None 测试对象是否不是 None.if obj 测试 bool(obj) 是否为 True.

if obj is not None test whether the object is not None. if obj tests whether bool(obj) is True.

有许多对象不是 None 而是 bool(obj) 为 False:例如,一个空列表、一个空字典、一个空集、一个空字符串...

There are many objects which are not None but for which bool(obj) is False: for instance, an empty list, an empty dict, an empty set, an empty string. . .

当你想测试一个对象是否不是 None 时,使用 if obj is not None.if obj 仅在您想测试一般虚假"时使用 - 其定义是依赖于对象的.

Use if obj is not None when you want to test if an object is not None. Use if obj only if you want to test for general "falseness" -- whose definition is object-dependent.

这篇关于if &lt;obj&gt; 之间的区别如果 &lt;obj&gt;不是无的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆