gpt4 book ai didi

python - 'is' 运算符在 Python 中有什么作用?

转载 作者:太空狗 更新时间:2023-10-29 21:26:49 24 4
gpt4 key购买 nike

我当时(也许是错误的)认为 is 运算符正在进行 id() 比较。

>>> x = 10
>>> y = 10
>>> id(x)
1815480092
>>> id(y)
1815480092
>>> x is y
True

但是,有了val is not None,似乎没那么简单。

>>> id(not None)
2001680
>>> id(None)
2053536
>>> val = 10
>>> id(val)
1815480092
>>> val is not None
True

那么,“is”运算符是做什么的呢?难道只是我猜想的对象id比较?如果是这样,val is not None 在 Python 中被解释为 not (val is None)?

最佳答案

您错过了不是也是运算符

没有 is,常规的 not 运算符返回一个 bool 值:

>>> not None
True

not None 因此是 None 的反向 bool “值”。在 bool 上下文中,None 为 false:

>>> bool(None)
False

所以 not None 是 bool 值 True

NoneTrue 也是对象,并且都有一个内存地址(值 id() 为 CPython 实现返回 python ):

>>> id(True)
4440103488
>>> id(not None)
4440103488
>>> id(None)
4440184448

is 测试两个引用是否指向同一个对象;如果某物是同一个对象,它也将具有相同的 id()is 返回一个 bool 值,TrueFalse

is notis 运算符的逆运算。在一个运算符中,它等效于 not (op1 is op2)。它应该被读作 op1(不是 op2):

>>> 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 - 'is' 运算符在 Python 中有什么作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18275616/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com