“ is”运算符在Python中做什么?
问题内容:
我(可能是错误地)认为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
那么,“是”运算符是做什么的?我只是猜想对象ID比较?如果是这样,val is not None
则在Python中解释为not (val is None)
?
问题答案:
你错过了这is not
是一个操作符 太 。
如果不使用is
,则常规not
运算符将返回一个布尔值:
>>> not None
True
not None
因此是的反布尔“值” None
。在布尔上下文中None
为false:
>>> bool(None)
False
not None
布尔值也是如此True
。
两者None
并True
有对象了,而且都有一个内存地址(该值id()
对CPython的Python实现收益):
>>> id(True)
4440103488
>>> id(not None)
4440103488
>>> id(None)
4440184448
is
测试两个引用是否指向 同一对象 ;
如果某物是同一对象,那么它也将具有相同的对象id()
。is
返回一个布尔值,True
或False
。
is not
是is
运算符的逆数。not (op1 is op2)
在一个运算符中,它等于。它应该 不 被理解为op1 is (not 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