問題:
I would like to be able to get the name of a variable as a string but I don't know if Python has that much introspection capabilities.我希望能夠以字符串的形式獲取變量的名稱,但我不知道 Python 是否具有那麼多的內省功能。 Something like:就像是:
>>> print(my_var.__name__)
'my_var'
I want to do that because I have a bunch of variables I'd like to turn into a dictionary like :我想這樣做是因爲我有一堆變量,我想變成像這樣的字典:
bar = True
foo = False
>>> my_dict = dict(bar=bar, foo=foo)
>>> print my_dict
{'foo': False, 'bar': True}
But I'd like something more automatic than that.但我想要比這更自動的東西。
Python have locals()
and vars()
, so I guess there is a way. Python 有locals()
和vars()
,所以我想有一種方法。
解決方案:
參考一: https://stackoom.com/question/AiF8參考二: Simpler way to create dictionary of separate variables?