我已经读了如何获得一个函数名作为字符串?。
如何对变量做同样的事情呢?与函数相反,Python变量没有__name__属性。
换句话说,如果我有一个变量,比如:
foo = dict()
foo['bar'] = 2
我正在寻找一个函数/属性,例如retrieve_name(),以便从这个列表中创建一个DataFrame in Pandas,其中列名由实际字典的名称给出:
# List of dictionaries for my DataFrame
list_of_dicts = [n_jobs, users, queues, priorities]
columns = [retrieve_name(d) for d in list_of_dicts]
我有一个方法,虽然不是最有效的…它的工作原理!(它不涉及任何花哨的模块)。
基本上,它将你的变量ID与globals()变量ID进行比较,然后返回匹配的名称。
def getVariableName(variable, globalVariables=globals().copy()):
""" Get Variable Name as String by comparing its ID to globals() Variables' IDs
args:
variable(var): Variable to find name for (Obviously this variable has to exist)
kwargs:
globalVariables(dict): Copy of the globals() dict (Adding to Kwargs allows this function to work properly when imported from another .py)
"""
for globalVariable in globalVariables:
if id(variable) == id(globalVariables[globalVariable]): # If our Variable's ID matches this Global Variable's ID...
return globalVariable # Return its name from the Globals() dict
每当我必须这样做时,主要是在与前端通信json模式和常量时,我定义了一个类,如下所示
class Param:
def __init__(self, name, value):
self.name = name
self.value = value
然后用名称和值定义变量。
frame_folder_count = Param({'name':'frame_folder_count', 'value':10})
现在可以使用对象访问名称和值。
>>> frame_folder_count.name
'frame_folder_count'