What is the id( ) function used for?

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

    The is operator uses it to check whether two objects are identical (as opposed to equal). The actual value that is returned from id() is pretty much never used for anything because it doesn't really have a meaning, and it's platform-dependent.

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-11-22 10:59

    I have an idea to use value of id() in logging.
    It's cheap to get and it's quite short.
    In my case I use tornado and id() would like to have an anchor to group messages scattered and mixed over file by web socket.

    0 讨论(0)
  • 2020-11-22 11:00

    I am starting out with python and I use id when I use the interactive shell to see whether my variables are assigned to the same thing or if they just look the same.

    Every value is an id, which is a unique number related to where it is stored in the memory of the computer.

    0 讨论(0)
  • 2020-11-22 11:01

    It is the address of the object in memory, exactly as the doc says. However, it has metadata attached to it, properties of the object and location in the memory is needed to store the metadata. So, when you create your variable called list, you also create metadata for the list and its elements.

    So, unless you an absolute guru in the language you can't determine the id of the next element of your list based on the previous element, because you don't know what the language allocates along with the elements.

    0 讨论(0)
  • 2020-11-22 11:03

    Rob's answer (most voted above) is correct. I would like to add that in some situations using IDs is useful as it allows for comparison of objects and finding which objects refer to your objects.

    The later usually helps you for example to debug strange bugs where mutable objects are passed as parameter to say classes and are assigned to local vars in a class. Mutating those objects will mutate vars in a class. This manifests itself in strange behavior where multiple things change at the same time.

    Recently I had this problem with a Python/Tkinter app where editing text in one text entry field changed the text in another as I typed :)

    Here is an example on how you might use function id() to trace where those references are. By all means this is not a solution covering all possible cases, but you get the idea. Again IDs are used in the background and user does not see them:

    class democlass:
        classvar = 24
    
        def __init__(self, var):
            self.instancevar1 = var
            self.instancevar2 = 42
    
        def whoreferencesmylocalvars(self, fromwhere):
            return {__l__: {__g__
                        for __g__ in fromwhere
                            if not callable(__g__) and id(eval(__g__)) == id(getattr(self,__l__))
                        }
                    for __l__ in dir(self)
                        if not callable(getattr(self, __l__)) and __l__[-1] != '_'
                    }
    
        def whoreferencesthisclassinstance(self, fromwhere):
            return {__g__
                        for __g__ in fromwhere
                            if not callable(__g__) and id(eval(__g__)) == id(self)
                    }
    
    a = [1,2,3,4]
    b = a
    c = b
    democlassinstance = democlass(a)
    d = democlassinstance
    e = d
    f = democlassinstance.classvar
    g = democlassinstance.instancevar2
    
    print( 'My class instance is of', type(democlassinstance), 'type.')
    print( 'My instance vars are referenced by:', democlassinstance.whoreferencesmylocalvars(globals()) )
    print( 'My class instance is referenced by:', democlassinstance.whoreferencesthisclassinstance(globals()) )
    

    OUTPUT:

    My class instance is of <class '__main__.democlass'> type.
    My instance vars are referenced by: {'instancevar2': {'g'}, 'classvar': {'f'}, 'instancevar1': {'a', 'c', 'b'}}
    My class instance is referenced by: {'e', 'd', 'democlassinstance'}
    

    Underscores in variable names are used to prevent name colisions. Functions use "fromwhere" argument so that you can let them know where to start searching for references. This argument is filled by a function that lists all names in a given namespace. Globals() is one such function.

    0 讨论(0)
提交回复
热议问题