简体   繁体   中英

How does “is” work in python?

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.

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

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 .

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

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM