2015年5月5日 星期二

[ Python 常見問題 ] Difference between '==' and 'is' operator

Source From Here
Question
I've got a python program where two variables are set to the value 'public'. In a conditional expression I have the comparison var1 is var2 which fails, but if I change it to var1 == var2 it returns True. now if I open my python interpreter and do the same "is" comparison it succeeds:
>>> s1 = 'public'
>>> s2 = 'public'
>>> s2 is s1
True


How-To
is is identity testing, == is equality testing. what happens in your code would be emulated in the interpreter like this:
>>> a = 'pub'
>>> b = ''.join(['p', 'u', 'b'])
>>> a == b
True
>>> a is b
False

Supplement
Is there a difference between `==` and `is` in Python?
is will return True if two variables point to the same object== if the objects referred to by the variables are equal (__eq__).


沒有留言:

張貼留言

[Git 常見問題] error: The following untracked working tree files would be overwritten by merge

  Source From  Here 方案1: // x -----删除忽略文件已经对 git 来说不识别的文件 // d -----删除未被添加到 git 的路径中的文件 // f -----强制运行 #   git clean -d -fx 方案2: 今天在服务器上  gi...