如何查看引用对象的所有变量?

时间:2015-06-18 02:47:05

标签: python variables reference

在我对Python的理解中,当我分配

A = 1

变量A是对值为1的对象的引用,也可以由其他变量引用。

如何查看/打印/返回引用此对象的所有变量?

1 个答案:

答案 0 :(得分:2)

首先,获得dictionary of all variables currently in scope and their values

d = dict(globals(), **locals())

然后在字典中创建一个列表,其中值与您感兴趣的对象匹配:

[ref for ref in d if d[ref] is obj]

e.g:

A = [1,2,3]
B = A
C = B
d = dict(globals(), **locals())
print [ref for ref in d if d[ref] is C]

输出:

['A', 'C', 'B']