teh*_*van 88
根据Python 文档,该sys
模块包含一个函数:
import sys
sys.getrefcount(object) #-- Returns the reference count of the object.
Run Code Online (Sandbox Code Playgroud)
由于对象arg临时引用,通常比您预期的高1.
有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)
Run Code Online (Sandbox Code Playgroud)
然后function(SomeObject)
提供'7',
sub_function(SomeObject)
提供'5',
sub_sub_function(SomeObject)
提供'3',并
sys.getrefcount(SomeObject)
提供'2'.
换句话说:如果使用sys.getrefcount()
,则必须了解函数调用深度.因为gc.get_referrers()
可能必须过滤引用列表.
我建议进行手动引用计数,例如"隔离更改",即"如果在别处引用则克隆".
小智 7
import ctypes
my_var = 'hello python'
my_var_address = id(my_var)
ctypes.c_long.from_address(my_var_address).value
Run Code Online (Sandbox Code Playgroud)
ctypes 将变量的地址作为参数。使用 ctypes 优于 sys.getRefCount 的优点是您不需要从结果中减去 1。
归档时间: |
|
查看次数: |
27173 次 |
最近记录: |