'==&quot之间是否有区别和“是”

发布于 2025-01-20 07:36:24 字数 531 浏览 1 评论 0 原文

我的 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 == 测试值是测试以查看它们是否是同一对象?

My Google-fu has failed me.

In Python, are the following two tests for equality equivalent?

n = 5
# Test one.
if n == 5:
    print 'Yay!'

# Test two.
if n is 5:
    print 'Yay!'

Does this hold true for objects where you would be comparing instances (a list say)?

Okay, so this kind of answers my question:

L = []
L.append(1)
if L == [1]:
    print 'Yay!'
# Holds true, but...

if L is [1]:
    print 'Yay!'
# Doesn't.

So == tests value where is tests to see if they are the same object?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(13

路还长,别太狂 2025-01-27 07:36:24

IS 将返回 true 如果两个变量指向同一对象(在内存), == 如果变量所指的对象是等于的。

>>> a = [1, 2, 3]
>>> b = a
>>> b is a 
True
>>> b == a
True

# Make a new copy of list `a` via the slice operator, 
# and assign it to variable `b`
>>> b = a[:] 
>>> b is a
False
>>> b == a
True

在您的情况下,第二个测试之所以起作用,是因为python加速了小整数对象,这是一个实现细节。 For larger integers, this does not work:

>>> 1000 is 10**3
False
>>> 1000 == 10**3
True

The same holds true for string literals:

>>> "a" is "a"
True
>>> "aa" is "a" * 2
True
>>> x = "a"
>>> "aa" is x * 2
False
>>> "aa" is intern(x*2)
True

Please see

is will return True if two variables point to the same object (in memory), == if the objects referred to by the variables are equal.

>>> a = [1, 2, 3]
>>> b = a
>>> b is a 
True
>>> b == a
True

# Make a new copy of list `a` via the slice operator, 
# and assign it to variable `b`
>>> b = a[:] 
>>> b is a
False
>>> b == a
True

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:

>>> 1000 is 10**3
False
>>> 1000 == 10**3
True

The same holds true for string literals:

>>> "a" is "a"
True
>>> "aa" is "a" * 2
True
>>> x = "a"
>>> "aa" is x * 2
False
>>> "aa" is intern(x*2)
True

Please see this question as well.

极度宠爱 2025-01-27 07:36:24

有一个简单的经验法则可以告诉您何时使用 == 或是。

  • == 值等于。当您想知道两个对象是否具有相同的值时,请使用它。
  • IS 参考等效。当您想知道两个引用是否参考同一对象时,请使用它。

通常,当您将某些内容与简单类型进行比较时,通常会检查 value equality ,因此应使用 == 。例如,您的示例的目的可能是检查x的值是否等于2( == ),而不是 x 是否实际上是指同一对象2。


要注意的其他内容:由于CPYTHON参考实现的工作方式,如果您错误地使用 IS 可以比较整数上的参考平等,那么您将获得意外且不一致的结果:

>>> a = 500
>>> b = 500
>>> a == b
True
>>> a is b
False

这几乎就是我们的内容预期: a b 具有相同的值,但是不同的实体。但是这个呢?

>>> c = 200
>>> d = 200
>>> c == d
True
>>> c is d
True

这与较早的结果不一致。这是怎么回事?事实证明,出于性能原因,Python Caches Integer对象的参考实现为-5..256。这是一个证明这一点的示例:

>>> for i in range(250, 260): a = i; print "%i: %s" % (i, a is int(str(i)));
... 
250: True
251: True
252: True
253: True
254: True
255: True
256: True
257: False
258: False
259: False

这是不使用 is 的另一个明显原因:当您错误地将其用于值平等时,该行为将留给实现。

There is a simple rule of thumb to tell you when to use == or is.

  • == 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 whether x 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:

>>> a = 500
>>> b = 500
>>> a == b
True
>>> a is b
False

That's pretty much what we expected: a and b have the same value, but are distinct entities. But what about this?

>>> c = 200
>>> d = 200
>>> c == d
True
>>> c is d
True

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:

>>> for i in range(250, 260): a = i; print "%i: %s" % (i, a is int(str(i)));
... 
250: True
251: True
252: True
253: True
254: True
255: True
256: True
257: False
258: False
259: False

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.

半仙 2025-01-27 07:36:24

== 之间的区别

是的,他们有一个非常重要的区别。

== :检查等效 - 语义是等效对象(不一定是同一对象)将测试为均等。如文档说

运算符&lt;,&gt;,==,&gt; =,&lt; =,and!=比较两个对象的值。

IS :检查身份 - 语义是对象(内存中保存) is 对象。同样,文档说

运算符是和不是对象身份的测试: x是y 是正确的
如果并且仅当 x y 是同一对象。对象身份是
使用 id()函数确定。 x不是y 产生逆
真实价值。

因此,对身份的检查与检查对象ID的平等相同。也就是说,

a is b

与以下内容相同:

id(a) == id(b)

其中 id 是返回整数“保证在同时存在的对象之间是唯一唯一的”函数(请参见 help> help> help(id) ),其中 a b 是任何任意对象。

其他使用方向,

您应该使用这些比较来为其语义使用。使用 IS 要检查身份, == 以检查平等。

因此,通常,我们使用来检查身份。当我们检查一个只能在存储器中仅存在的对象(在文档中称为“单例”)时,这通常很有用。

is 的用例包括:

  • none
  • 枚举值(使用枚举模块的枚举时)
  • 通常
  • 是由类别定义产生的类对象
  • 通常由功能定义产生的对象,
  • 该对象 函数定义对象。在内存中只能存在一次(通常是所有单例)
  • 您想要的特定对象,您想要的身份

常规用例, == 包括:

  • 数字,包括整数
  • 字符串
  • 列表
  • sets sets
  • dicturies dictuaries dictuaries
  • customable
  • 对象在大多数情况下

,对象再次,对于 == ,您想要的对象可能不是 same 对象,而是 等效一个

PEP 8指示

PEP 8,官方Python样式指南还提到

之类的单例进行比较
不是,从来都不是平等运算符。

另外,当您真正指的是时,请当心如果您的意思是,则如果x不是没有 -
例如,在测试默认为的变量或参数时
被设置为其他值。另一个值可能具有类型(这样
作为一个容器),在布尔上下文中可能是错误的!

从身份中推论平等

如果是正确的,那么平等可以通常被推断出 - 从逻辑上讲,如果对象本身是本身,则应与自身相等的测试。

在大多数情况下,此逻辑是正确的,但它依赖于 __ eq __ 特殊方法的实现。作为 docs 说,说,说,说说,

平等比较的默认行为( == != )是基于
对象的身份。因此,实例的平等比较
具有相同的身份会导致平等和平等比较
具有不同身份的实例导致不平等。一个
这种默认行为的动机是所有对象的愿望
应该是反身的(ie x是y表示x == y)。

为了一致性,建议:

平等比较应该是反身的。换句话说,相同
对象应比较相等:

x是y 暗示 x == y

我们可以看到,这是自定义对象的默认行为:

>>> class Object(object): pass
>>> obj = Object()
>>> obj2 = Object()
>>> obj == obj, obj is obj
(True, True)
>>> obj == obj2, obj is obj2
(False, False)

隔开效率通常也为true-由于并非平等,您通常可以推断它们不是同一对象。

由于可以自定义平等测试,因此对于所有类型的推断并不总是成立。

一个

例外的一个例外是 nan - 它始终测试与自身的测试:

>>> nan = float('nan')
>>> nan
nan
>>> nan is nan
True
>>> nan == nan           # !!!!!
False

检查身份的检查比检查平等要快得多(这可能需要递归检查成员)。

但是,它不能代替平等,而您可能会发现一个以上的对象等效。

请注意,比较列表和元组的平等将假定对象的身份相等(因为这是快速检查)。如果逻辑不一致,这可能会产生矛盾 - 因为它是 nan

>>> [nan] == [nan]
True
>>> (nan,) == (nan,)
True

一个警示性的故事:

问题是尝试使用 is 来比较整数。您不应该假设整数的实例与另一个参考获得的实例是相同的实例。这个故事解释了原因。

一位评论者的代码依赖于以下事实:小整数(-5至256)是Python中的单例,而不是检查平等。

哇,这可能会导致一些阴险的错误。我有一些检查A是否为B的代码,因为A和B通常数量很少。该错误仅在生产六个月后才发生,因为A和B终于足够大以至于没有缓存。 - GWG

它在开发中起作用。它可能已经通过了一些Unistests。

它在生产中起作用 - 直到该代码检查了大于256的整数,这时它的生产失败了。

这是一种生产故障,本来可以在代码审查中或可能与样式检查器一起捕获的失败。

让我强调: 请勿使用 is 来比较整数。

Is there a difference between == and is in Python?

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:

The operators <, >, ==, >=, <=, and != compare the values of two objects.

is: check for identity - the semantics are that the object (as held in memory) is the object. Again, the documentation says:

The operators is and is not test for object identity: x is y is true
if and only if x and y are the same object. Object identity is
determined using the id() function. x is not y yields the inverse
truth value.

Thus, the check for identity is the same as checking for the equality of the IDs of the objects. That is,

a is b

is the same as:

id(a) == id(b)

where id is the builtin function that returns an integer that "is guaranteed to be unique among simultaneously existing objects" (see help(id)) and where a and b 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
  • enum values (when using Enums from the enum module)
  • usually modules
  • usually class objects resulting from class definitions
  • usually function objects resulting from function definitions
  • anything else that should only exist once in memory (all singletons, generally)
  • a specific object that you want by identity

Usual use cases for == include:

  • numbers, including integers
  • strings
  • lists
  • sets
  • dictionaries
  • custom mutable objects
  • other builtin immutable objects, in most cases

The general use case, again, for ==, is the object you want may not be the same object, instead it may be an equivalent one

PEP 8 directions

PEP 8, the official Python style guide for the standard library also mentions two use-cases for is:

Comparisons to singletons like None should always be done with is or
is not, never the equality operators.

Also, beware of writing if x when you really mean if x is not None --
e.g. when testing whether a variable or argument that defaults to None
was set to some other value. The other value might have a type (such
as a container) that could be false in a boolean context!

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,

The default behavior for equality comparison (== and !=) is based on
the identity of the objects. Hence, equality comparison of instances
with the same identity results in equality, and equality comparison of
instances with different identities results in inequality. A
motivation for this default behavior is the desire that all objects
should be reflexive (i.e. x is y implies x == y).

and in the interests of consistency, recommends:

Equality comparison should be reflexive. In other words, identical
objects should compare equal:

x is y implies x == y

We can see that this is the default behavior for custom objects:

>>> class Object(object): pass
>>> obj = Object()
>>> obj2 = Object()
>>> obj == obj, obj is obj
(True, True)
>>> obj == obj2, obj is obj2
(False, False)

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:

>>> nan = float('nan')
>>> nan
nan
>>> nan is nan
True
>>> nan == nan           # !!!!!
False

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:

>>> [nan] == [nan]
True
>>> (nan,) == (nan,)
True

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.

Wow, this can lead to some insidious bugs. I had some code that checked if a is b, which worked as I wanted because a and b are typically small numbers. The bug only happened today, after six months in production, because a and b were finally large enough to not be cached. – gwg

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.

难忘№最初的完美 2025-01-27 07:36:24

== 确定值是否相等,而 确定它们是否是完全相同的对象。

== determines if the values are equal, while is determines if they are the exact same object.

写给空气的情书 2025-01-27 07:36:24

== 之间有什么区别?

== 是不同的比较!正如其他人已经说过的:

  • == 比较对象的值。
  • IS 比较对象的引用。

在Python名称中,请参阅对象,例如在这种情况下 value1 value2 请参阅 int 存储值 1000 实例代码>:

value1 = 1000
value2 = value1

在此处输入图像描述“

因为 value2 是指同一对象 is == 将给出 true true 代码>:

>>> value1 == value2
True
>>> value1 is value2
True

在下面的示例中,名称 value1 value2 请参阅不同的 int 实例,即使两者都存储相同的整数:

>>> value1 = 1000
>>> value2 = 1000

由于存储相同的值(整数) == 将为 true ,所以这就是为什么通常称为“值比较”的原因。但是,将返回 false ,因为这些是不同的对象:

>>> value1 == value2
True
>>> value1 is value2
False

何时使用?

通常,是一个更快的比较。这就是为什么cpython缓存(或 reuses 将是更好的术语)某些对象(例如小整数,某些字符串等)。即使不太可能)在没有警告的情况下改变。

则应仅使用 IS 是

,在中,您应该使用 == 检查平等性。

我可以自定义行为吗?

== 在其他答案中尚未提及的某些方面:它是 pythons“数据模型” 。这意味着可以使用 __ eq eq __ eq 方法。例如:

class MyClass(object):
    def __init__(self, val):
        self._value = val

    def __eq__(self, other):
        print('__eq__ method called')
        try:
            return self._value == other._value
        except AttributeError:
            raise TypeError('Cannot compare {0} to objects of type {1}'
                            .format(type(self), type(other)))

这只是一个人为的示例,可以说明该方法的确被称为:

>>> MyClass(10) == MyClass(10)
__eq__ method called
True

默认情况下(如果没有其他实现 __ eq __ 在类或超级类别中可以找到) __ eq __ eq __ eq __ 使用 IS :

class AClass(object):
    def __init__(self, value):
        self._value = value

>>> a = AClass(10)
>>> b = AClass(10)
>>> a == b
False
>>> a == a

因此,实现 __ eq __ 实际上重要的是,如果您想要“更多”,而不仅仅是自定义类的参考比较!

另一方面,您无法自定义检查。如果您有相同的参考,它将始终比较

这些比较会总是返回布尔值吗?

因为 __ EQ __ 可以重新实现或覆盖,因此不限于返回 true false 。它可以返回任何东西(但是在大多数情况下,它应该返回布尔值!)。

例如,使用numpy数组 == 将返回数组:

>>> import numpy as np
>>> np.arange(10) == 2
array([False, False,  True, False, False, False, False, False, False, False], dtype=bool)

但是 is 检查将始终返回 true false


1 作为评论中提到的亚伦大厅:

通常,您不应该做任何是true 是false 检查,因为通常使用这些检查“在将条件隐式转换为布尔值的上下文中(例如,在语句中,在中)。因此,执行是True 比较隐含的布尔演员所做的不仅仅是做布尔演员的工作更多的工作 - 您将自己限制在布尔人上(这不被视为Pythonic) 。

就像PEP8提到的那样:

不要将布尔值与 true false 使用 == 。。

 是:如果问候:
否:如果问候== true:
更糟糕的是:如果问候是真的:
 

What's the difference between is and ==?

== and is 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 and value2 refer to an int instance storing the value 1000:

value1 = 1000
value2 = value1

enter image description here

Because value2 refers to the same object is and == will give True:

>>> value1 == value2
True
>>> value1 is value2
True

In the following example the names value1 and value2 refer to different int instances, even if both store the same integer:

>>> value1 = 1000
>>> value2 = 1000

enter image description here

Because the same value (integer) is stored == will be True, that's why it's often called "value comparison". However is will return False because these are different objects:

>>> value1 == value2
True
>>> value1 is value2
False

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
    • True1
    • False1
    • NotImplemented
    • Ellipsis
    • __debug__
    • classes (for example int is int or int is float)
    • there could be additional constants in built-in modules or 3rd party modules. For example 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:

class MyClass(object):
    def __init__(self, val):
        self._value = val

    def __eq__(self, other):
        print('__eq__ method called')
        try:
            return self._value == other._value
        except AttributeError:
            raise TypeError('Cannot compare {0} to objects of type {1}'
                            .format(type(self), type(other)))

This is just an artificial example to illustrate that the method is really called:

>>> MyClass(10) == MyClass(10)
__eq__ method called
True

Note that by default (if no other implementation of __eq__ can be found in the class or the superclasses) __eq__ uses is:

class AClass(object):
    def __init__(self, value):
        self._value = value

>>> a = AClass(10)
>>> b = AClass(10)
>>> a == b
False
>>> a == a

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 return True or False. It could return anything (but in most cases it should return a boolean!).

For example with NumPy arrays the == will return an array:

>>> import numpy as np
>>> np.arange(10) == 2
array([False, False,  True, False, False, False, False, False, False, False], dtype=bool)

But is checks will always return True or False!


1 As Aaron Hall mentioned in the comments:

Generally you shouldn't do any is True or is False checks because one normally uses these "checks" in a context that implicitly converts the condition to a boolean (for example in an if statement). So doing the is 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:

Don't compare boolean values to True or False using ==.

Yes:   if greeting:
No:    if greeting == True:
Worse: if greeting is True:
泼猴你往哪里跑 2025-01-27 07:36:24

它们完全不同is 检查对象标识,而 == 检查相等性(这一概念取决于两个操作数的类型)。

is”似乎可以正确地处理小整数(例如 5 == 4+1),这只是一个幸运的巧合。这是因为 CPython 优化了范围 (-5到 256)通过使它们成为单例。此行为完全依赖于实现,并且不保证在各种较小的转换操作下保留。

例如,Python 3.5 也使短字符串成为单例,但对它们进行切片会破坏这种行为:

>>> "foo" + "bar" == "foobar"
True
>>> "foo" + "bar" is "foobar"
True
>>> "foo"[:] + "bar" == "foobar"
True
>>> "foo"[:] + "bar" is "foobar"
False

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:

>>> "foo" + "bar" == "foobar"
True
>>> "foo" + "bar" is "foobar"
True
>>> "foo"[:] + "bar" == "foobar"
True
>>> "foo"[:] + "bar" is "foobar"
False
烟花肆意 2025-01-27 07:36:24

https://docs.python.org/library/stdtypes.html#comparisons

is 身份测试
== 测试相等性

每个(小)整数值都映射到单个值,因此每 3 个都是相同且相等的。这是一个实现细节,但不是语言规范的一部分

https://docs.python.org/library/stdtypes.html#comparisons

is tests for identity
== tests for equality

Each (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

素衣风尘叹 2025-01-27 07:36:24

您的答案是正确的。 操作员比较两个对象的身份。 == 操作员比较两个对象的值。

一旦创建对象的身份就永远不会改变。您可能会认为它是内存中对象的地址。

您可以通过定义 __ 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__.

马蹄踏│碎落叶 2025-01-27 07:36:24

查看 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).

猫弦 2025-01-27 07:36:24

简而言之, IS 检查两个引用是否指向同一对象。 == 检查两个对象是否具有相同的值。

a=[1,2,3]
b=a        #a and b point to the same object
c=list(a)  #c points to different object 

if a==b:
    print('#')   #output:#
if a is b:
    print('##')  #output:## 
if a==c:
    print('###') #output:## 
if a is c:
    print('####') #no output as c and a point to different object 

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.

a=[1,2,3]
b=a        #a and b point to the same object
c=list(a)  #c points to different object 

if a==b:
    print('#')   #output:#
if a is b:
    print('##')  #output:## 
if a==c:
    print('###') #output:## 
if a is c:
    print('####') #no output as c and a point to different object 
浅唱々樱花落 2025-01-27 07:36:24

正如本文中的其他人在详细介绍 == 之间的区别是用于比较对象或变量时,我将强调主要是 == 的比较可以给出不同的结果,我敦促程序员仔细使用它们。

对于字符串比较,请确保使用 == 而不是

str = 'hello'
if (str is 'hello'):
    print ('str is hello')
if (str == 'hello'):
    print ('str == hello')

out:

str is hello
str == hello

但是在下面的示例中 == IS 将获得不同的结果:

str2 = 'hello sam'
    if (str2 is 'hello sam'):
        print ('str2 is hello sam')
    if (str2 == 'hello sam'):
        print ('str2 == hello sam')

OUT:

str2 == hello sam

结论和分析:

使用 is 仔细以比较字符串之间。
由于用于比较对象的,并且在python 3+中,每个变量(例如字符串)解释为对象,让我们看看上面段落中发生了什么。

在python中,有 id 函数显示对象在其寿命中的唯一常数。此ID在Python解释器的后端使用,用 关键字比较两个对象。

str = 'hello'
id('hello')
> 140039832615152
id(str)
> 140039832615152

str2 = 'hello sam'
id('hello sam')
> 140039832615536
id(str2)
> 140039832615792

As the other people in this post answer the question in details the difference between == and is for comparing Objects or variables, I would emphasize mainly the comparison between is 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 of is:

str = 'hello'
if (str is 'hello'):
    print ('str is hello')
if (str == 'hello'):
    print ('str == hello')

Out:

str is hello
str == hello

But in the below example == and is will get different results:

str2 = 'hello sam'
    if (str2 is 'hello sam'):
        print ('str2 is hello sam')
    if (str2 == 'hello sam'):
        print ('str2 == hello sam')

Out:

str2 == hello sam

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 using is keyword.

str = 'hello'
id('hello')
> 140039832615152
id(str)
> 140039832615152

But

str2 = 'hello sam'
id('hello sam')
> 140039832615536
id(str2)
> 140039832615792
姐不稀罕 2025-01-27 07:36:24

正如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 and foo is None mean the same. However the is test is faster and the Pythonic convention is to use foo 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 is bar.

True and False are also (now) singletons, but there is no use-case for foo == True and no use case for foo is True.

残花月 2025-01-27 07:36:24

他们中的大多数已经回答了这一点。作为附加说明(基于我的理解和实验,但不是来自记录的来源),该声明

==如果变量引用的对象相等

从上述答案等于

==如果变量引用的对象是相等的,并且属于同一类型/class

的对象

。我根据以下测试得出了这个结论:

list1 = [1,2,3,4]
tuple1 = (1,2,3,4)

print(list1)
print(tuple1)
print(id(list1))
print(id(tuple1))

print(list1 == tuple1)
print(list1 is tuple1)

这里列表的内容和元组相同,但类型/类别不同。

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

== if the objects referred to by the variables are equal

from above answers should be read as

== if the objects referred to by the variables are equal and objects belonging to the same type/class

. I arrived at this conclusion based on the below test:

list1 = [1,2,3,4]
tuple1 = (1,2,3,4)

print(list1)
print(tuple1)
print(id(list1))
print(id(tuple1))

print(list1 == tuple1)
print(list1 is tuple1)

Here the contents of the list and tuple are same but the type/class are different.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文