Simpler way to create dictionary of separate variables?

前端 未结 27 2637
名媛妹妹
名媛妹妹 2020-11-22 02:42

I would like to be able to get the name of a variable as a string but I don\'t know if Python has that much introspection capabilities. Something like:

>&         


        
27条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2020-11-22 03:30

    In reading the thread, I saw an awful lot of friction. It's easy enough to give a bad answer, then let someone give the correct answer. Anyway, here is what I found.

    From: [effbot.org] (http://effbot.org/zone/python-objects.htm#names)

    The names are a bit different — they’re not really properties of the object, and the object itself doesn't know what it’s called.

    An object can have any number of names, or no name at all.

    Names live in namespaces (such as a module namespace, an instance namespace, a function’s local namespace).

    Note: that it says the object itself doesn’t know what it’s called, so that was the clue. Python objects are not self-referential. Then it says, Names live in namespaces. We have this in TCL/TK. So maybe my answer will help (but it did help me)

    
        jj = 123
        print eval("'" + str(id(jj)) + "'")
        print dir()
    
    

    166707048
    ['__builtins__', '__doc__', '__file__', '__name__', '__package__', 'jj']
    

    So there is 'jj' at the end of the list.

    Rewrite the code as:

    
        jj = 123
        print eval("'" + str(id(jj)) + "'")
        for x in dir():
            print id(eval(x))
    
    
    161922920
    ['__builtins__', '__doc__', '__file__', '__name__', '__package__', 'jj']
    3077447796
    136515736
    3077408320
    3077656800
    136515736
    161922920
    

    This nasty bit of code id's the name of variable/object/whatever-you-pedantics-call-it.

    So, there it is. The memory address of 'jj' is the same when we look for it directly, as when we do the dictionary look up in global name space. I'm sure you can make a function to do this. Just remember which namespace your variable/object/wypci is in.

    QED.

提交回复
热议问题