What is the id( ) function used for?

前端 未结 13 1007
傲寒
傲寒 2020-11-22 10:51

I read the Python 2 docs and noticed the id() function:

Return the “identity” of an object. This is an integer (or long integer) which is

13条回答
  •  长发绾君心
    2020-11-22 10:57

    That's the identity of the location of the object in memory...

    This example might help you understand the concept a little more.

    foo = 1
    bar = foo
    baz = bar
    fii = 1
    
    print id(foo)
    print id(bar)
    print id(baz)
    print id(fii)
    
    > 1532352
    > 1532352
    > 1532352
    > 1532352
    

    These all point to the same location in memory, which is why their values are the same. In the example, 1 is only stored once, and anything else pointing to 1 will reference that memory location.

提交回复
热议问题