Python 'is' vs JavaScript ===

前端 未结 4 1434
一向
一向 2021-02-04 03:01

The Python use of \'is\' seems to be similar to JavaScript \'===\' but not quite.

Here they talk about exact instances: http://www.learnpython.org/en/Conditions

<
4条回答
  •  孤城傲影
    2021-02-04 03:25

    >>> a = "Hello, World!!!"
    >>> b = "Hello, World!!!"
    >>> a is b
    False
    

    However note that:

    >>> a = "Bob"
    >>> b = "Bob"
    >>> a is b
    True
    

    In this case it condition was True because the compiler is free to intern string literals, and thus reuse the same object, and it does do that with small strings. However there is no guarantee as to when this happens of if this happens at all and the behaviour changes between versions and implementations.


    A realiable False output should be:

    >>> a = 'Hello, World!!!!'[:-1]
    >>> b = 'Hello, World!!!!'[:-1]
    >>> a is b
    False
    

    Or anything that actually computes the strings.

提交回复
热议问题