Python中的“是"运算符是做什么的? [英] What does 'is' operator do in Python?
问题描述
我(可能是错误地)认为is
运算符正在进行id()比较.
I was (maybe wrongfully) thinking that is
operator is doing id() comparison.
>>> x = 10
>>> y = 10
>>> id(x)
1815480092
>>> id(y)
1815480092
>>> x is y
True
但是,使用val is not None
似乎并不那么简单.
However, with val is not None
, it seems like that it's not that simple.
>>> id(not None)
2001680
>>> id(None)
2053536
>>> val = 10
>>> id(val)
1815480092
>>> val is not None
True
然后,是"运算符是做什么的?我只是猜想对象ID比较?如果是这样,val is not None
在Python中会解释为not (val is None)
吗?
Then, what does 'is' operator do? Is it just object id comparison just I conjectured? If so, val is not None
is interpreted in Python as not (val is None)
?
推荐答案
您错过了is not
也是运算符 .
在没有is
的情况下,常规not
运算符将返回布尔值:
Without is
, the regular not
operator returns a boolean:
>>> not None
True
因此,
not None
是None
的反布尔值".在布尔上下文中,None
为假:
not None
is thus the inverse boolean 'value' of None
. In a boolean context None
is false:
>>> bool(None)
False
所以not None
是布尔值True
.
None
和True
也是对象,并且都具有内存地址(对于CPython Python实现,返回值id()
):
Both None
and True
are objects too, and both have a memory address (the value id()
returns for the CPython implementation of Python):
>>> id(True)
4440103488
>>> id(not None)
4440103488
>>> id(None)
4440184448
is
测试两个引用是否指向同一对象;如果某物是同一对象,则它也将具有相同的id()
. is
返回布尔值True
或False
.
is
tests if two references are pointing to the same object; if something is the same object, it'll have the same id()
as well. is
returns a boolean value, True
or False
.
is not
是is
运算符的反函数.在一个运算符中,它等效于not (op1 is op2)
.在此处应 not 读为op1 is (not op2)
is not
is the inverse of the is
operator. It is the equivalent of not (op1 is op2)
, in one operator. It should not be read as op1 is (not op2)
here:
>>> 1 is not None # is 1 a different object from None?
True
>>> 1 is (not None) # is 1 the same object as True?
False
这篇关于Python中的“是"运算符是做什么的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!