How does “is” work in python?

人盡茶涼 提交于 2021-01-21 07:12:22

问题


Can please someone explain how one may use 'is' in an 'if' condition. I am working with the fractions module, and I'm having some trouble:

>>> Fraction(0, 1) is 0
False
>>> float(Fraction(0, 1))
0.0
>>> float(Fraction(0,1)) is 0.0
False

The only thing I found to work is:

>>> F = Fraction(a,b)
>>> if F >= 0:
...     if F(0, 1) <= 0:
...                      ...

Is there a way to use 'is' here? Thanks.


回答1:


is checks for object identity. It returns true if two names refer to the same object. One typical usecase is to check if a name refers to None:

if foo is None:
    # do stuff



回答2:


The is operator in python is used to check if two variables are pointing to the very same object and is not meant to be used to check about numeric equality. You should use == for that instead.

For example consider that

(1000 + 1000) is (1000 + 1000)

returns False.




回答3:


From the documentation:

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.

What you want here is ==, to test whether two objects are equal or equivalent by comparing the values and not the identities.

A trivial example (in CPython that may differ in other implementations):

>>> 1 + 2 == 3.0
True
>>> 1 + 2 is 3.0
False
>>> 1 + 2 is 3
True
>>> id(1 + 2)
4298185512
>>> id(3.0)
4298194656
>>> id(3)
4298185512



回答4:


a is b is equivalent to id(a) == id(b)




回答5:


Quote from http://docs.python.org/library/operator.html:

operator.is_(a, b) Return a is b. Tests object identity.



来源:https://stackoverflow.com/questions/6235684/how-does-is-work-in-python

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!