How to write a function to return the variable name?

后端 未结 6 1373
自闭症患者
自闭症患者 2020-12-04 03:59

I want a function that can return the variable/object name as str like this :

def get_variable_name (input_variable):
    ## some codes

>>get_variable         


        
6条回答
  •  青春惊慌失措
    2020-12-04 04:59

    In general it is not possible. When you pass something to a function, you are passing the object, not the name. The same object can have many names or no names. What is the function supposed to do if you call get_variable_name(37)? You should think about why you want to do this, and try to find another way to accomplish your real task.

    Edit: If you want get_variable_name(37) to return 37, then if you do a=37 and then do get_variable_name(a), that will also return 37. Once inside the function, it has no way of knowing what the object's "name" was outside.

提交回复
热议问题