我已经读了如何获得一个函数名作为字符串?。
如何对变量做同样的事情呢?与函数相反,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]
每当我必须这样做时,主要是在与前端通信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'
如果目标是帮助您跟踪变量,您可以编写一个简单的函数来标记变量并返回其值和类型。例如,假设i_f=3.01,并将其舍入为一个名为i_n的整数以用于代码,然后需要一个字符串i_s用于报告。
def whatis(string, x):
print(string+' value=',repr(x),type(x))
return string+' value='+repr(x)+repr(type(x))
i_f=3.01
i_n=int(i_f)
i_s=str(i_n)
i_l=[i_f, i_n, i_s]
i_u=(i_f, i_n, i_s)
## make report that identifies all types
report='\n'+20*'#'+'\nThis is the report:\n'
report+= whatis('i_f ',i_f)+'\n'
report+=whatis('i_n ',i_n)+'\n'
report+=whatis('i_s ',i_s)+'\n'
report+=whatis('i_l ',i_l)+'\n'
report+=whatis('i_u ',i_u)+'\n'
print(report)
这将在每次调用时打印到窗口中用于调试,并为书面报告生成一个字符串。唯一的缺点是每次调用函数时都必须输入两次变量。
I am a Python newbie and found this very useful way to log my efforts as I program and try to cope with all the objects in Python. One flaw is that whatis() fails if it calls a function described outside the procedure where it is used. For example, int(i_f) was a valid function call only because the int function is known to Python. You could call whatis() using int(i_f**2), but if for some strange reason you choose to define a function called int_squared it must be declared inside the procedure where whatis() is used.
如果有两个值相同的变量,前面的一些情况会失败。所以提醒它很方便:
定义函数:
# Variable to string of variable name
def var_name(variable,i=0):
results = []
for name in globals():
if eval(name) == variable:
results.append(name)
if len(results) > 1:
print('Warning:' )
print(' var_name() has found',len(results), 'possible outcomes.')
print(' Please choose the suitable parameter "i". Where "i" is the index')
print(' that matches your choice from the list below.')
print(' ',results) ; print('')
return results[i]
Use:
var_1 = 10
var_name(var_1) # Output will be "var_1"
如果你有两个相同值的变量,比如var_1 = 8和var_2 = 8,那么就会出现一个警告。
var_1 = 8
var_2 = 8
var_name(var_2) # Output will be "var_1" too but Warning will appear