if A vs if A is not None: [英] if A vs if A is not None:
问题描述
我可以使用吗:
if A:
代替
if A is not None:
后者看起来很冗长.有区别吗?
The latter seems so verbose. Is there a difference?
推荐答案
声明
if A:
将调用 A.__nonzero__()
(参见 特殊方法名称文档)并使用该函数的返回值.总结如下:
will call A.__nonzero__()
(see Special method names documentation) and use the return value of that function. Here's the summary:
调用以实现真值测试和内置操作bool()
;应该返回 False
或 True
,或者它们的等效整数 0
或 1
.如果未定义此方法,则调用 __len__()
(如果已定义),并且如果其结果非零,则该对象被视为真.如果一个类既没有定义 __len__()
也没有定义 __nonzero__()
,那么它的所有实例都被认为是真的.
object.__nonzero__(self)
Called to implement truth value testing and the built-in operation
bool()
; should returnFalse
orTrue
, or their integer equivalents0
or1
. 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__nonzero__()
, all its instances are considered true.
另一方面,
if A is not None:
比较仅引用A
和None
,看是否相同.
compares only the reference A
with None
to see whether it is the same or not.
这篇关于if A vs if A is not None:的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!