Cla*_*ell 182 python comparison nonetype
可能重复:
`==`运算符何时不等于`is`运算符?(蟒蛇)
我使用的是Python 2.x.
我比较时编辑给了我一个"警告"下划线my_var == None,但是当我使用时没有警告my_var is None.
我在Python shell中做了一个测试,并确定两者都是有效的语法,但我的编辑器似乎说这my_var is None是首选.
是这种情况,如果是这样,为什么?
mgi*_*son 230
使用is时要核对对象的身份(如检查,看看是否var是None).使用==时要检查的平等(例如是var等于3?).
您可以拥有my_var == None将返回的自定义类True
例如:
class Negator(object):
def __eq__(self,other):
return not other
thing = Negator()
print thing == None #True
print thing is None #False
Run Code Online (Sandbox Code Playgroud)
is检查对象标识.只有一个对象None,所以当你这样做时my_var is None,你要检查它们是否实际上是同一个对象(而不仅仅是等效的对象)
换句话说,==是检查等价(从对象到对象定义),而is检查对象标识:
lst = [1,2,3]
lst == lst[:] # This is True since the lists are "equivalent"
lst is lst[:] # This is False since they're actually different objects
Run Code Online (Sandbox Code Playgroud)
use*_*342 113
is当将任意对象与单身对比时通常是优选的,None因为它更快且更可预测.is总是按对象标识进行比较,而==做什么取决于操作数的确切类型,甚至取决于它们的排序.
PEP 8支持这一建议,它明确指出 "与单身人士的比较,如"无"应该始终使用,is或者is not从不使用相等运算符."
我最近遇到了可能出错的地方。
import numpy as np
nparray = np.arange(4)
# Works
def foo_is(x=None):
if x is not None:
print(x[1])
foo_is()
foo_is(nparray)
# Code below raises
# ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
def foo_eq(x=None):
if x != None:
print(x[1])
foo_eq()
foo_eq(nparray)
Run Code Online (Sandbox Code Playgroud)
我创建了一个函数,该函数可以选择将 numpy 数组作为参数,并在包含该数组时进行更改。如果我使用不等式运算符测试其包含情况!=,则会引发 ValueError (参见上面的代码)。如果我使用is not none,代码可以正常工作。