For all built-in Python objects (like strings, lists, dicts, functions, etc.), if x is y, then x==y is also True. (对于所有内置的Python对象(如字符串,列表,字典,函数等),如果x为y,则x == y也为True。)
Not always. (不总是。) NaN is a counterexample. (NaN是一个反例。) But usually , identity ( is
) implies equality ( ==
). (但通常 ,身份( is
)表示相等( ==
)。) The converse is not true: Two distinct objects can have the same value. (反之则不成立:两个不同的对象可以具有相同的值。)
Also, is it generally considered better to just use '==' by default, even when comparing int or Boolean values? (另外,即使比较int或Boolean值,通常还是最好还是默认使用'=='吗?)
You use ==
when comparing values and is
when comparing identities. (您可以使用==
比较值,并在is
比较的身份时。)
When comparing ints (or immutable types in general), you pretty much always want the former. (比较整数(或通常不可变的类型)时,您几乎总是希望使用前者。) There's an optimization that allows small integers to be compared with is
, but don't rely on it. (有一个优化允许将小整数与is
进行比较,但不要依赖它。)
For boolean values, you shouldn't be doing comparisons at all. (对于布尔值,您根本不应该进行比较。) Instead of: (代替:)
if x == True:
# do something
write: (写:)
if x:
# do something
For comparing against None
, is None
is preferred over == None
. (为了与None
比较, is None
优于== None
。)
I've always liked to use 'is' because I find it more aesthetically pleasing and pythonic (which is how I fell into this trap...), but I wonder if it's intended to just be reserved for when you care about finding two objects with the same id. (我一直喜欢使用'is',因为我发现它在审美上更令人愉悦和pythonic(这就是我陷入这个陷阱的方式...),但是我想知道是否打算仅在您关心找到两个对象时才保留它?具有相同ID的对象。)
Yes, that's exactly what it's for. (是的,这就是它的用途。)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…