【发布时间】:2015-09-03 12:29:21
【问题描述】:
在我对 Python 的理解中,当我赋值时
A = 1
变量A 是对具有值1 的对象的引用,该对象也可以被其他变量引用。
如何查看/打印/返回所有引用此对象的变量?
【问题讨论】:
标签: python variables reference
在我对 Python 的理解中,当我赋值时
A = 1
变量A 是对具有值1 的对象的引用,该对象也可以被其他变量引用。
如何查看/打印/返回所有引用此对象的变量?
【问题讨论】:
标签: python variables reference
首先,获取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']
【讨论】: