Understanding Python's “is” operator

前端 未结 11 2281
别那么骄傲
别那么骄傲 2020-11-21 22:42

The is operator does not match the values of the variables, but the instances themselves.

What does it really mean?

11条回答
  •  天涯浪人
    2020-11-21 23:05

    x is y is same as id(x) == id(y), comparing identity of objects.

    As @tomasz-kurgan pointed out in the comment below is operator behaves unusually with certain objects.

    E.g.

    >>> class A(object):
    ...   def foo(self):
    ...     pass
    ... 
    >>> a = A()
    >>> a.foo is a.foo
    False
    >>> id(a.foo) == id(a.foo)
    True
    

    Ref;
    https://docs.python.org/2/reference/expressions.html#is-not
    https://docs.python.org/2/reference/expressions.html#id24

提交回复
热议问题