'==&quot之间是否有区别和“是”
我的 google-fu 使我失败了。
在Python中,以下两个测试是否相等?
n = 5
# Test one.
if n == 5:
print 'Yay!'
# Test two.
if n is 5:
print 'Yay!'
对于您将要比较实例的对象(<代码>列表 Say),这是否成立?
好的,所以这种答案是我的问题:
L = []
L.append(1)
if L == [1]:
print 'Yay!'
# Holds true, but...
if L is [1]:
print 'Yay!'
# Doesn't.
so ==
测试值是测试以查看它们是否是同一对象?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(13)
IS
将返回true
如果两个变量指向同一对象(在内存),==
如果变量所指的对象是等于的。在您的情况下,第二个测试之所以起作用,是因为python加速了小整数对象,这是一个实现细节。 For larger integers, this does not work:
The same holds true for string literals:
Please see
is
will returnTrue
if two variables point to the same object (in memory),==
if the objects referred to by the variables are equal.In your case, the second test only works because Python caches small integer objects, which is an implementation detail. For larger integers, this does not work:
The same holds true for string literals:
Please see this question as well.
有一个简单的经验法则可以告诉您何时使用
==
或是。==
是值等于。当您想知道两个对象是否具有相同的值时,请使用它。IS
是参考等效。当您想知道两个引用是否参考同一对象时,请使用它。通常,当您将某些内容与简单类型进行比较时,通常会检查 value equality ,因此应使用
==
。例如,您的示例的目的可能是检查x的值是否等于2(==
),而不是x
是否实际上是指同一对象2。要注意的其他内容:由于CPYTHON参考实现的工作方式,如果您错误地使用
IS
可以比较整数上的参考平等,那么您将获得意外且不一致的结果:这几乎就是我们的内容预期:
a
和b
具有相同的值,但是不同的实体。但是这个呢?这与较早的结果不一致。这是怎么回事?事实证明,出于性能原因,Python Caches Integer对象的参考实现为-5..256。这是一个证明这一点的示例:
这是不使用
is
的另一个明显原因:当您错误地将其用于值平等时,该行为将留给实现。There is a simple rule of thumb to tell you when to use
==
oris
.==
is for value equality. Use it when you would like to know if two objects have the same value.is
is for reference equality. Use it when you would like to know if two references refer to the same object.In general, when you are comparing something to a simple type, you are usually checking for value equality, so you should use
==
. For example, the intention of your example is probably to check whether x has a value equal to 2 (==
), not whetherx
is literally referring to the same object as 2.Something else to note: because of the way the CPython reference implementation works, you'll get unexpected and inconsistent results if you mistakenly use
is
to compare for reference equality on integers:That's pretty much what we expected:
a
andb
have the same value, but are distinct entities. But what about this?This is inconsistent with the earlier result. What's going on here? It turns out the reference implementation of Python caches integer objects in the range -5..256 as singleton instances for performance reasons. Here's an example demonstrating this:
This is another obvious reason not to use
is
: the behavior is left up to implementations when you're erroneously using it for value equality.是的,他们有一个非常重要的区别。
==
:检查等效 - 语义是等效对象(不一定是同一对象)将测试为均等。如文档说:IS
:检查身份 - 语义是对象(内存中保存) is 对象。同样,文档说:因此,对身份的检查与检查对象ID的平等相同。也就是说,
与以下内容相同:
其中
id
是返回整数“保证在同时存在的对象之间是唯一唯一的”函数(请参见help> help> help(id)
),其中a
和b
是任何任意对象。其他使用方向,
您应该使用这些比较来为其语义使用。使用
IS
要检查身份,==
以检查平等。因此,通常,我们使用
是
来检查身份。当我们检查一个只能在存储器中仅存在的对象(在文档中称为“单例”)时,这通常很有用。is
的用例包括:none
常规用例,
==
包括:,对象再次,对于
==
,您想要的对象可能不是 same 对象,而是 等效一个PEP 8指示
PEP 8,官方Python样式指南还提到
是
:从身份中推论平等
如果
为
是正确的,那么平等可以通常被推断出 - 从逻辑上讲,如果对象本身是本身,则应与自身相等的测试。在大多数情况下,此逻辑是正确的,但它依赖于
__ eq __
特殊方法的实现。作为 docs 说,说,说,说说,为了一致性,建议:
我们可以看到,这是自定义对象的默认行为:
隔开效率通常也为true-由于并非平等,您通常可以推断它们不是同一对象。
由于可以自定义平等测试,因此对于所有类型的推断并不总是成立。
一个
例外的一个例外是
nan
- 它始终测试与自身的测试:检查身份的检查比检查平等要快得多(这可能需要递归检查成员)。
但是,它不能代替平等,而您可能会发现一个以上的对象等效。
请注意,比较列表和元组的平等将假定对象的身份相等(因为这是快速检查)。如果逻辑不一致,这可能会产生矛盾 - 因为它是
nan
:一个警示性的故事:
问题是尝试使用
is
来比较整数。您不应该假设整数的实例与另一个参考获得的实例是相同的实例。这个故事解释了原因。一位评论者的代码依赖于以下事实:小整数(-5至256)是Python中的单例,而不是检查平等。
它在开发中起作用。它可能已经通过了一些Unistests。
它在生产中起作用 - 直到该代码检查了大于256的整数,这时它的生产失败了。
这是一种生产故障,本来可以在代码审查中或可能与样式检查器一起捕获的失败。
让我强调: 请勿使用
is
来比较整数。Yes, they have a very important difference.
==
: check for equality - the semantics are that equivalent objects (that aren't necessarily the same object) will test as equal. As the documentation says:is
: check for identity - the semantics are that the object (as held in memory) is the object. Again, the documentation says:Thus, the check for identity is the same as checking for the equality of the IDs of the objects. That is,
is the same as:
where
id
is the builtin function that returns an integer that "is guaranteed to be unique among simultaneously existing objects" (seehelp(id)
) and wherea
andb
are any arbitrary objects.Other Usage Directions
You should use these comparisons for their semantics. Use
is
to check identity and==
to check equality.So in general, we use
is
to check for identity. This is usually useful when we are checking for an object that should only exist once in memory, referred to as a "singleton" in the documentation.Use cases for
is
include:None
Usual use cases for
==
include:The general use case, again, for
==
, is the object you want may not be the same object, instead it may be an equivalent onePEP 8 directions
PEP 8, the official Python style guide for the standard library also mentions two use-cases for
is
:Inferring equality from identity
If
is
is true, equality can usually be inferred - logically, if an object is itself, then it should test as equivalent to itself.In most cases this logic is true, but it relies on the implementation of the
__eq__
special method. As the docs say,and in the interests of consistency, recommends:
We can see that this is the default behavior for custom objects:
The contrapositive is also usually true - if somethings test as not equal, you can usually infer that they are not the same object.
Since tests for equality can be customized, this inference does not always hold true for all types.
An exception
A notable exception is
nan
- it always tests as not equal to itself:Checking for identity can be much a much quicker check than checking for equality (which might require recursively checking members).
But it cannot be substituted for equality where you may find more than one object as equivalent.
Note that comparing equality of lists and tuples will assume that identity of objects are equal (because this is a fast check). This can create contradictions if the logic is inconsistent - as it is for
nan
:A Cautionary Tale:
The question is attempting to use
is
to compare integers. You shouldn't assume that an instance of an integer is the same instance as one obtained by another reference. This story explains why.A commenter had code that relied on the fact that small integers (-5 to 256 inclusive) are singletons in Python, instead of checking for equality.
It worked in development. It may have passed some unittests.
And it worked in production - until the code checked for an integer larger than 256, at which point it failed in production.
This is a production failure that could have been caught in code review or possibly with a style-checker.
Let me emphasize: do not use
is
to compare integers.==
确定值是否相等,而 确定它们是否是完全相同的对象。==
determines if the values are equal, whileis
determines if they are the exact same object.是
和==
之间有什么区别?==
和是
是不同的比较!正如其他人已经说过的:==
比较对象的值。IS
比较对象的引用。在Python名称中,请参阅对象,例如在这种情况下
value1
和value2
请参阅int
存储值1000
实例代码>:因为
value2
是指同一对象is
和==
将给出true
true 代码>:在下面的示例中,名称
value1
和value2
请参阅不同的int
实例,即使两者都存储相同的整数:由于存储相同的值(整数)
==
将为true
,所以这就是为什么通常称为“值比较”的原因。但是,是
将返回false
,因为这些是不同的对象:何时使用?
通常,
是
是一个更快的比较。这就是为什么cpython缓存(或 reuses 将是更好的术语)某些对象(例如小整数,某些字符串等)。即使不太可能)在没有警告的情况下改变。则应仅使用 IS 是 。
想检查两个对象是否真的是相同的对象(不仅是相同的“值”), 一个示例可以是如果 you 将单例对象用作常数。
想要将一个值与
无
true
1false
1通知
省略号
__ debug __
int是int
或int是float
),在中,您应该使用
==
检查平等性。我可以自定义行为吗?
==
在其他答案中尚未提及的某些方面:它是 pythons“数据模型” 。这意味着可以使用__ eq eq __ eq
这只是一个人为的示例,可以说明该方法的确被称为:
默认情况下(如果没有其他实现
__ eq __
在类或超级类别中可以找到)__ eq __ eq __ eq __
使用 IS :因此,实现
__ eq __
实际上重要的是,如果您想要“更多”,而不仅仅是自定义类的参考比较!另一方面,您无法自定义
是
检查。如果您有相同的参考,它将始终比较 。这些比较会总是返回布尔值吗?
因为
__ EQ __
可以重新实现或覆盖,因此不限于返回true
或false
。它可以返回任何东西(但是在大多数情况下,它应该返回布尔值!)。例如,使用numpy数组
==
将返回数组:但是
is
检查将始终返回true
或false
呢1 作为评论中提到的亚伦大厅:
通常,您不应该做任何
是true
或是false
检查,因为通常使用这些检查“在将条件隐式转换为布尔值的上下文中(例如,在语句中,在中)。因此,执行
是True
比较和隐含的布尔演员所做的不仅仅是做布尔演员的工作更多的工作 - 您将自己限制在布尔人上(这不被视为Pythonic) 。就像PEP8提到的那样:
What's the difference between
is
and==
?==
andis
are different comparison! As others already said:==
compares the values of the objects.is
compares the references of the objects.In Python names refer to objects, for example in this case
value1
andvalue2
refer to anint
instance storing the value1000
:Because
value2
refers to the same objectis
and==
will giveTrue
:In the following example the names
value1
andvalue2
refer to differentint
instances, even if both store the same integer:Because the same value (integer) is stored
==
will beTrue
, that's why it's often called "value comparison". Howeveris
will returnFalse
because these are different objects:When to use which?
Generally
is
is a much faster comparison. That's why CPython caches (or maybe reuses would be the better term) certain objects like small integers, some strings, etc. But this should be treated as implementation detail that could (even if unlikely) change at any point without warning.You should only use
is
if you:want to check if two objects are really the same object (not just the same "value"). One example can be if you use a singleton object as constant.
want to compare a value to a Python constant. The constants in Python are:
None
True
1False
1NotImplemented
Ellipsis
__debug__
int is int
orint is float
)np.ma.masked
from the NumPy module)In every other case you should use
==
to check for equality.Can I customize the behavior?
There is some aspect to
==
that hasn't been mentioned already in the other answers: It's part of Pythons "Data model". That means its behavior can be customized using the__eq__
method. For example:This is just an artificial example to illustrate that the method is really called:
Note that by default (if no other implementation of
__eq__
can be found in the class or the superclasses)__eq__
usesis
:So it's actually important to implement
__eq__
if you want "more" than just reference-comparison for custom classes!On the other hand you cannot customize
is
checks. It will always compare just if you have the same reference.Will these comparisons always return a boolean?
Because
__eq__
can be re-implemented or overridden, it's not limited to returnTrue
orFalse
. It could return anything (but in most cases it should return a boolean!).For example with NumPy arrays the
==
will return an array:But
is
checks will always returnTrue
orFalse
!1 As Aaron Hall mentioned in the comments:
Generally you shouldn't do any
is True
oris False
checks because one normally uses these "checks" in a context that implicitly converts the condition to a boolean (for example in anif
statement). So doing theis True
comparison and the implicit boolean cast is doing more work than just doing the boolean cast - and you limit yourself to booleans (which isn't considered pythonic).Like PEP8 mentions:
它们完全不同。
is
检查对象标识,而==
检查相等性(这一概念取决于两个操作数的类型)。“
is
”似乎可以正确地处理小整数(例如 5 == 4+1),这只是一个幸运的巧合。这是因为 CPython 优化了范围 (-5到 256)通过使它们成为单例。此行为完全依赖于实现,并且不保证在各种较小的转换操作下保留。例如,Python 3.5 也使短字符串成为单例,但对它们进行切片会破坏这种行为:
They are completely different.
is
checks for object identity, while==
checks for equality (a notion that depends on the two operands' types).It is only a lucky coincidence that "
is
" seems to work correctly with small integers (e.g. 5 == 4+1). That is because CPython optimizes the storage of integers in the range (-5 to 256) by making them singletons. This behavior is totally implementation-dependent and not guaranteed to be preserved under all manner of minor transformative operations.For example, Python 3.5 also makes short strings singletons, but slicing them disrupts this behavior:
https://docs.python.org/library/stdtypes.html#comparisons
is
身份测试==
测试相等性每个(小)整数值都映射到单个值,因此每 3 个都是相同且相等的。这是一个实现细节,但不是语言规范的一部分
https://docs.python.org/library/stdtypes.html#comparisons
is
tests for identity==
tests for equalityEach (small) integer value is mapped to a single value, so every 3 is identical and equal. This is an implementation detail, not part of the language spec though
您的答案是正确的。
是
操作员比较两个对象的身份。==
操作员比较两个对象的值。一旦创建对象的身份就永远不会改变。您可能会认为它是内存中对象的地址。
您可以通过定义
__ cmp __
方法或a 丰富的比较__ eq __
之类的方法。Your answer is correct. The
is
operator compares the identity of two objects. The==
operator compares the values of two objects.An object's identity never changes once it has been created; you may think of it as the object's address in memory.
You can control comparison behaviour of object values by defining a
__cmp__
method or a rich comparison method like__eq__
.查看 Stack Overflow 问题Python 的“is”运算符对整数的行为异常。
它主要归结为“
is
”检查它们是否是同一个对象,而不仅仅是彼此相等(256 以下的数字是一种特殊情况)。Have a look at Stack Overflow question Python's “is” operator behaves unexpectedly with integers.
What it mostly boils down to is that "
is
" checks to see if they are the same object, not just equal to each other (the numbers below 256 are a special case).简而言之,
IS
检查两个引用是否指向同一对象。==
检查两个对象是否具有相同的值。In a nutshell,
is
checks whether two references point to the same object or not.==
checks whether two objects have the same value or not.正如本文中的其他人在详细介绍
==
和之间的区别是
用于比较对象或变量时,我将强调主要是是
和==
的比较可以给出不同的结果,我敦促程序员仔细使用它们。对于字符串比较,请确保使用
==
而不是是
:out:
但是在下面的示例中
==
和IS
将获得不同的结果:OUT:
结论和分析:
使用 is 仔细以比较字符串之间。
由于
是
用于比较对象的,并且在python 3+中,每个变量(例如字符串)解释为对象,让我们看看上面段落中发生了什么。在python中,有
id
函数显示对象在其寿命中的唯一常数。此ID在Python解释器的后端使用,用 关键字比较两个对象。但
As the other people in this post answer the question in details the difference between
==
andis
for comparing Objects or variables, I would emphasize mainly the comparison betweenis
and==
for strings which can give different results and I would urge programmers to carefully use them.For string comparison, make sure to use
==
instead ofis
:Out:
But in the below example
==
andis
will get different results:Out:
Conclusion and Analysis:
Use
is
carefully to compare between strings.Since
is
for comparing objects and since in Python 3+ every variable such as string interpret as an object, let's see what happened in above paragraphs.In python there is
id
function that shows a unique constant of an object during its lifetime. This id is using in back-end of Python interpreter to compare two objects usingis
keyword.But
正如John Feminella所说,大多数时候您都会使用==和!= = =因为您的目标是比较价值。我只是想对您的剩余时间进行分类:
有一个和只有一个非类型的实例,即无是单身人士。因此,
foo ==无
和foo是无
表示相同的意思。但是,IS
测试更快,Pythonic约定是使用foo是无
。如果您正在进行一些内省或用垃圾收集进行烦恼或检查您的自定义字符串Indivenning小工具正在工作或类似的工作,那么您可能有一个用例/代码>。
TROUKY和FALSE也是(现在)Singletons,但是
foo == true
也没有用例,并且foo的用例为true
。As John Feminella said, most of the time you will use == and != because your objective is to compare values. I'd just like to categorise what you would do the rest of the time:
There is one and only one instance of NoneType i.e. None is a singleton. Consequently
foo == None
andfoo is None
mean the same. However theis
test is faster and the Pythonic convention is to usefoo is None
.If you are doing some introspection or mucking about with garbage collection or checking whether your custom-built string interning gadget is working or suchlike, then you probably have a use-case for
foo
isbar
.True and False are also (now) singletons, but there is no use-case for
foo == True
and no use case forfoo is True
.他们中的大多数已经回答了这一点。作为附加说明(基于我的理解和实验,但不是来自记录的来源),该声明
从上述答案等于
。我根据以下测试得出了这个结论:
这里列表的内容和元组相同,但类型/类别不同。
Most of them already answered to the point. Just as an additional note (based on my understanding and experimenting but not from a documented source), the statement
from above answers should be read as
. I arrived at this conclusion based on the below test:
Here the contents of the list and tuple are same but the type/class are different.