Python中的“是"运算符是做什么的? [英] What does 'is' operator do in Python?

查看:89
本文介绍了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 NoneNone的反布尔值".在布尔上下文中,None为假:

not None is thus the inverse boolean 'value' of None. In a boolean context None is false:

>>> bool(None)
False

所以not None是布尔值True.

NoneTrue也是对象,并且都具有内存地址(对于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返回布尔值TrueFalse.

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 notis运算符的反函数.在一个运算符中,它等效于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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆