About the changing id of an immutable string

后端 未结 5 1758
暗喜
暗喜 2020-11-22 03:33

Something about the id of objects of type str (in python 2.7) puzzles me. The str type is immutable, so I would expect that once it is

5条回答
  •  不思量自难忘°
    2020-11-22 04:07

    This behavior is specific to the Python interactive shell. If I put the following in a .py file:

    print id('so')
    print id('so')
    print id('so')
    

    and execute it, I receive the following output:

    2888960
    2888960
    2888960
    

    In CPython, a string literal is treated as a constant, which we can see in the bytecode of the snippet above:

      2           0 LOAD_GLOBAL              0 (id)
                  3 LOAD_CONST               1 ('so')
                  6 CALL_FUNCTION            1
                  9 PRINT_ITEM          
                 10 PRINT_NEWLINE       
    
      3          11 LOAD_GLOBAL              0 (id)
                 14 LOAD_CONST               1 ('so')
                 17 CALL_FUNCTION            1
                 20 PRINT_ITEM          
                 21 PRINT_NEWLINE       
    
      4          22 LOAD_GLOBAL              0 (id)
                 25 LOAD_CONST               1 ('so')
                 28 CALL_FUNCTION            1
                 31 PRINT_ITEM          
                 32 PRINT_NEWLINE       
                 33 LOAD_CONST               0 (None)
                 36 RETURN_VALUE  
    

    The same constant (i.e. the same string object) is loaded 3 times, so the IDs are the same.

提交回复
热议问题