What is the id( ) function used for?

前端 未结 13 1233
傲寒
傲寒 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:14

    Your post asks several questions:

    What is the number returned from the function?

    It is "an integer (or long integer) which is guaranteed to be unique and constant for this object during its lifetime." (Python Standard Library - Built-in Functions) A unique number. Nothing more, and nothing less. Think of it as a social-security number or employee id number for Python objects.

    Is it the same with memory addresses in C?

    Conceptually, yes, in that they are both guaranteed to be unique in their universe during their lifetime. And in one particular implementation of Python, it actually is the memory address of the corresponding C object.

    If yes, why doesn't the number increase instantly by the size of the data type (I assume that it would be int)?

    Because a list is not an array, and a list element is a reference, not an object.

    When do we really use id( ) function?

    Hardly ever. id() (or its equivalent) is used in the is operator.

提交回复
热议问题