【问题标题】:How can I view all of the variables that refer to an object? [duplicate]如何查看引用对象的所有变量? [复制]
【发布时间】:2015-09-03 12:29:21
【问题描述】:

在我对 Python 的理解中,当我赋值时

A = 1

变量A 是对具有值1 的对象的引用,该对象也可以被其他变量引用。

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

【问题讨论】:

    标签: python variables reference


    【解决方案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']
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-03-01
      • 2011-04-02
      • 1970-01-01
      • 2011-06-19
      • 1970-01-01
      • 1970-01-01
      • 2020-01-09
      • 2016-08-13
      相关资源
      最近更新 更多