+ -
当前位置:首页 → 问答吧 → python is

python is

时间:2010-11-16

来源:互联网

python is是种很特殊的语法,你在其它的语言应该不会见到这样的用法,今天就来说说这个把。
python is 按照自字面的意思就是什么东西是什么的,比如he is a boy,他是一个大男孩,而我们一般在写python程序的时候,也会用到一些判断,有的时候也会用到python is,比如判断下这个字符是否为none。

下面是python is的例子,比如我们来判断下一个字符串。
a = 'abc'

if a is not None:
print 'a is not none'

输出的结果是 a is not none

那现在就有个疑问了,什么时候会出现None,不然我们就不用python is来判断了。
一般在python里面我们的调用一些方法的话,会返回None,而不是其它的值,比如python 列表操作方法里面的python append()就是返回
None,其它的一些方法也会返回None,所以python is就有用武之地了。

作者: cucugbgb   发布时间: 2010-11-16

The operators is and is not test for object identity: x is y is true if and only if x and y are the same object. x is not y yields the inverse truth value. --python reference

这玩意其实就是用来判断x和y是不是同一个对象。
我感觉类似于C++中的指针比较,比如MFC中经常有
  if (m_hWnd == GetFocus())
    ......
这样的语句,语意上应该与python的is差不太多吧

作者: ncoder   发布时间: 2010-11-17