This question already has answers here:
Find all references to an object in python
(2个答案)
四年前关闭。
在我对Python的理解中,当我指定
变量
如何查看/打印/返回引用此对象的所有变量?
然后在字典中创建所有引用的列表,其中的值与您感兴趣的对象匹配:
例如:
输出:
(2个答案)
四年前关闭。
在我对Python的理解中,当我指定
A = 1
变量
A
是对值1
的对象的引用,其他变量也可以引用该对象。如何查看/打印/返回引用此对象的所有变量?
最佳答案
首先,得到一个dictionary of all variables currently in scope and their values。
d = dict(globals(), **locals())
然后在字典中创建所有引用的列表,其中的值与您感兴趣的对象匹配:
[ref for ref in d if d[ref] is obj]
例如:
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']