【问题标题】:Is there a way to get the current ref count of an object in Python?有没有办法在 Python 中获取对象的当前引用计数?
【发布时间】:2009-02-04 07:32:51
【问题描述】:

有没有办法在 Python 中获取对象的当前引用计数?

【问题讨论】:

    标签: python refcounting


    【解决方案1】:

    根据 Python documentationsys 模块包含一个函数:

    import sys
    sys.getrefcount(object) #-- Returns the reference count of the object.
    

    由于对象 arg 临时引用,通常比您预期的高 1。

    【讨论】:

    【解决方案2】:

    使用gc 模块,垃圾收集器的接口,您可以调用gc.get_referrers(foo) 来获取所有引用foo 的列表。

    因此,len(gc.get_referrers(foo)) 将为您提供该列表的长度:推荐人的数量,这就是您所追求的。

    另请参阅gc module documentation

    【讨论】:

    • 还应该提到计数将+1,因为gc列表也引用了对象。
    • 我认为@Dan 的答案是正确的: >>> import gc >>> class Bar(): ... pass ... >>> b = Bar() >>> len (gc.get_referrers(b)) 1 >>> gc.get_referrers(b) [{'b': <__main__.bar instance at>, 'Bar': main.Bar at 0x7f1f010d6530>, 'builtins': builtin' (built-in)>, 'package': 无, 'gc': , 'name': 'main', 'doc': None}]跨度>
    • @tehvan 的回答 (sys.getrefcount(object)) 比 len(gc.get_referrers(foo)) 更直接,如果你真的只需要数字的话。
    • 在 Android 的 qpython3 中,它给出了错误的答案。每次。
    【解决方案3】:

    gc.get_referrers()sys.getrefcount()。但是,很难看出sys.getrefcount(X) 是如何达到传统引用计数的目的的。考虑:

    import sys
    
    def function(X):
        sub_function(X)
    
    def sub_function(X):
        sub_sub_function(X)
    
    def sub_sub_function(X):
        print sys.getrefcount(X)
    

    然后function(SomeObject) 提供“7”,
    sub_function(SomeObject) 提供“5”,
    sub_sub_function(SomeObject) 提供“3”,
    sys.getrefcount(SomeObject) 提供“2”。

    换句话说:如果您使用sys.getrefcount(),您必须了解函数调用深度。对于gc.get_referrers(),可能需要过滤推荐人列表。

    我建议手动引用计数用于“隔离更改”,即“如果在其他地方引用则克隆”。

    【讨论】:

      【解决方案4】:
      import ctypes
      
      my_var = 'hello python'
      my_var_address = id(my_var)
      
      ctypes.c_long.from_address(my_var_address).value
      

      ctypes 将变量的地址作为参数。 使用ctypes 而不是sys.getRefCount 的优点是您不需要从结果中减去1。

      【讨论】:

      • 虽然有趣但不应该使用这种方法:1)阅读代码时没有人会理解发生了什么 2)它取决于 CPython 的实现细节:id 是对象的地址和确切的地址PyObject 的内存布局。如果需要,只需从 getrefcount() 中减去 1。
      【解决方案5】:

      Python 中的每个对象都有一个引用计数和一个指向类型的指针。 我们可以通过 sys 模块 获取对象的当前引用计数。您可以使用 sys.getrefcount(object)但请记住,将对象传递给 getrefcount() 会将引用计数增加 1

      import sys
      
      name = "Steve"
      
      # 2 references, 1 from the name variable and 1 from getrefcount
      sys.getrefcount(name)
      

      【讨论】:

        猜你喜欢
        • 2011-06-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多