How to retrieve a variable's name in python at runtime?

后端 未结 8 1498
悲哀的现实
悲哀的现实 2020-11-28 13:33

Is there a way to know, during run-time, a variable\'s name (from the code)? Or do variable\'s names forgotten during compilation (byte-code or not)?

e.g.:



        
8条回答
  •  一个人的身影
    2020-11-28 13:57

    Variable names don't get forgotten, you can access variables (and look which variables you have) by introspection, e.g.

    >>> i = 1
    >>> locals()["i"]
    1
    

    However, because there are no pointers in Python, there's no way to reference a variable without actually writing its name. So if you wanted to print a variable name and its value, you could go via locals() or a similar function. ([i] becomes [1] and there's no way to retrieve the information that the 1 actually came from i.)

提交回复
热议问题