简体   繁体   English

“是”如何在 python 中工作?

[英]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?有没有办法在这里使用'is'? 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.运算符isis not测试 object 身份:当且仅当 x 和 y 相同 object 时, x is y为真。 x is not y yields the inverse truth value. x is not y产生逆真值。

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):一个简单的例子(在CPython中可能在其他实现中有所不同):

>>> 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. python 中的is运算符用于检查两个变量是否指向同一个 object,并不用于检查数值相等性。 You should use == for that instead.你应该使用==来代替。

For example consider that例如考虑

(1000 + 1000) is (1000 + 1000)

returns False .返回False

is checks for object identity. is object 身份。 It returns true if two names refer to the same object.如果两个名称引用相同的 object,则返回 true。 One typical usecase is to check if a name refers to None :一个典型的用例是检查名称是否引用None

if foo is None:
    # do stuff

a is b is equivalent to id(a) == id(b) a is b等价于id(a) == id(b)

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

operator.is_(a, b) Return a is b. operator.is_(a, b) 返回 a 是 b。 Tests object identity.测试 object 身份。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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