What is the id( ) function used for?

前端 未结 13 1008
傲寒
傲寒 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 11:06

    I'm a little bit late and i will talk about Python3. To understand what id() is and how it (and Python) works, consider next example:

    >>> x=1000
    >>> y=1000
    >>> id(x)==id(y)
    False
    >>> id(x)
    4312240944
    >>> id(y)
    4312240912
    >>> id(1000)
    4312241104
    >>> x=1000
    >>> id(x)
    4312241104
    >>> y=1000
    >>> id(y)
    4312241200
    

    You need to think about everything on the right side as objects. Every time you make assignment - you create new object and that means new id. In the middle you can see a "wild" object which is created only for function - id(1000). So, it's lifetime is only for that line of code. If you check the next line - you see that when we create new variable x, it has the same id as that wild object. Pretty much it works like memory address.

提交回复
热议问题