【发布时间】:2009-02-04 07:32:51
【问题描述】:
有没有办法在 Python 中获取对象的当前引用计数?
【问题讨论】:
标签: python refcounting
有没有办法在 Python 中获取对象的当前引用计数?
【问题讨论】:
标签: python refcounting
根据 Python documentation,sys 模块包含一个函数:
import sys
sys.getrefcount(object) #-- Returns the reference count of the object.
由于对象 arg 临时引用,通常比您预期的高 1。
【讨论】:
使用gc 模块,垃圾收集器的接口,您可以调用gc.get_referrers(foo) 来获取所有引用foo 的列表。
因此,len(gc.get_referrers(foo)) 将为您提供该列表的长度:推荐人的数量,这就是您所追求的。
【讨论】:
sys.getrefcount(object)) 比 len(gc.get_referrers(foo)) 更直接,如果你真的只需要数字的话。
有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(),可能需要过滤推荐人列表。
我建议手动引用计数用于“隔离更改”,即“如果在其他地方引用则克隆”。
【讨论】:
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。
【讨论】:
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)
【讨论】: