python – 如果A vs if A不是None:

我可以用吗:

if A:

代替

if A is not None:

后者似乎很冗长。有区别吗?

该声明

if A:

将调用A .__非零__()(参见Special method names文档),并使用该函数的返回值。这里是总结:

object.__nonzero__(self)

Called to implement truth value testing and the built-in operation bool(); should return False or True, or their integer equivalents 0 or 1. 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与无,以查看它是否相同。

http://stackoverflow.com/questions/7816363/if-a-vs-if-a-is-not-none

本站文章除注明转载外,均为本站原创或编译
转载请明显位置注明出处:python – 如果A vs if A不是None: