if A vs if A is not None: [英] if A vs if A is not None:

查看:56
本文介绍了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();应该返回 FalseTrue,或者它们的等效整数 01.如果未定义此方法,则调用 __len__()(如果已定义),并且如果其结果非零,则该对象被视为真.如果一个类既没有定义 __len__() 也没有定义 __nonzero__(),那么它的所有实例都被认为是真的.

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:

比较引用ANone,看是否相同.

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屋!

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