How can I view all of the variables that refer to an object?
本问题已经有最佳答案,请猛点这里访问。
在我对python的理解中,
1 | A = 1 |
变量
如何查看/打印/返回引用此对象的所有变量?
首先,获取当前作用域中所有变量及其值的字典。
1 | d = dict(globals(), **locals()) |
然后在字典中创建所有引用的列表,其中值与您感兴趣的对象匹配:
1 | [ref for ref in d if d[ref] is obj] |
例如:
1 2 3 4 5 | A = [1,2,3] B = A C = B d = dict(globals(), **locals()) print [ref for ref in d if d[ref] is C] |
输出:
1 | ['A', 'C', 'B'] |