What is the id( ) function used for?

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

提交回复
热议问题