我希望能够以字符串的形式获取变量的名称,但我不知道Python是否有那么多的自省功能。喜欢的东西:
>>> print(my_var.__name__)
'my_var'
我想这样做是因为我有一堆变量,我想把它们转换成一个字典,比如:
bar = True
foo = False
>>> my_dict = dict(bar=bar, foo=foo)
>>> print my_dict
{'foo': False, 'bar': True}
但我想要更自动的。
Python有locals()和vars(),所以我猜有一种方法。
我根据这个问题的答案写了一个简洁有用的函数。我把它放在这里,以防有用。
def what(obj, callingLocals=locals()):
"""
quick function to print name of input and value.
If not for the default-Valued callingLocals, the function would always
get the name as "obj", which is not what I want.
"""
for k, v in list(callingLocals.items()):
if v is obj:
name = k
print(name, "=", obj)
用法:
>> a = 4
>> what(a)
a = 4
>>|
大多数对象没有__name__属性。(类、函数和模块可以;还有其他内置类型吗?)
除了print("my_var"),你还期望print(my_var.__name__)有什么?你能直接使用字符串吗?
你可以"slice" a dict:
def dict_slice(D, keys, default=None):
return dict((k, D.get(k, default)) for k in keys)
print dict_slice(locals(), ["foo", "bar"])
# or use set literal syntax if you have a recent enough version:
print dict_slice(locals(), {"foo", "bar"})
另外:
throw = object() # sentinel
def dict_slice(D, keys, default=throw):
def get(k):
v = D.get(k, throw)
if v is not throw:
return v
if default is throw:
raise KeyError(k)
return default
return dict((k, get(k)) for k in keys)