python变量名包括_Python – 获取全局范围内对象的所有变量名
我將用一個例子來解釋:
list_1 = [1, 2, 3]
list_2 = list_3 = list_1 # reference copy
print(magic_method(list_1))
# Should print ['list_1', 'list_2', 'list_3']
set_1 = {'a', 'b'}
print(magic_method(set_1))
# Should print ['set_1']
要求:返回指向同一引用的所有變量的名稱.用python完全可以嗎?
我正在思考迭代于globals()和locals()以及等同id的行.有更好的嗎?
最佳答案 對于全局變量,您可以:
def magic_method(obj):
return [name for name, val in globals().items() if val is obj]
如果您也想要本地名稱,可以使用inspect模塊:
def magic_method(obj):
import inspect
frame = inspect.currentframe()
try:
names = [name for name, val in frame.f_back.f_locals.items() if val is obj]
names += [name for name, val in frame.f_back.f_globals.items()
if val is obj and name not in names]
return names
finally:
del frame
然后:
list_1 = [1, 2, 3]
list_2 = list_1
def my_fun():
list_3 = list_1
list_2 = list_1
print(magic_method(list_1))
my_fun()
>>> ['list_3', 'list_1', 'list_2']
總結
以上是生活随笔為你收集整理的python变量名包括_Python – 获取全局范围内对象的所有变量名的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 多边形之间相交求交点的算法_路径规划算法
- 下一篇: elementui :on-remove