Python布尔比较

Python Boolean comparison

我正在测试 Python 的布尔表达式。当我运行以下代码时:

x = 3
print type(x)
print (x is int)
print (x is not int)

我得到以下结果:

<type 'int'>
False
True

为什么明明 x 是整数类型时 (x is int) 返回 false 而 (x is not int) 返回 true?

最好的方法是使用 isinstance()

所以在你的情况下:

x = 3
print isinstance(x, int)

关于 python is

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.

取自docs

如果你想使用 is 你应该这样做:

>>> print (type(x) is int)
True

尝试将这些输入您的解释器:

type(x)
int
x is 3
x is not 3
type(x) is int
type(x) is not int

x is int 为假的原因是它询问数字 3 和 Python int class 是否代表同一个对象。很明显这是错误的。

附带说明一下,如果您不确切了解 Python 的 is 关键字,它可能会以一些意想不到的方式发挥作用,如果您几乎肯定应该避免使用它你一直在测试平等。也就是说,在您的实际程序之外进行试验是一个非常好的主意。