为什么sys.getrefcount()返回2? [英] Why does sys.getrefcount() return 2?

查看:432
本文介绍了为什么sys.getrefcount()返回2?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

据我了解,sys.getrefcount()返回一个对象的引用数,在下列情况下应该为1:

  import sys,numpy 
a = numpy.array([1.2,3.4])
print sys.getrefcount(a)

然而,原来是2!所以,如果我:

  del a 

请问numpy.array([1.2,3.4])对象仍然在那里(没有垃圾回收)?

解决方案当你调用 getrefcount()时,引用会被值复制到函数的参数中,临时提升对象的引用计数。这是第二个参考文献的来源。



这在文档


返回的计数通常比您预期的高
,它包含(临时)引用作为参数
getrefcount()。


至于你的第二个问题:


如果我del a,那么将numpy.array([1.2, 3.4)]对象仍然存在(没有垃圾回收)?

getrefcount()退出时,数组的引用计数将返回1,随后的 del a 会释放内存。


As I understand, sys.getrefcount() returns the number of references of an object, which "should" be 1 in the following case:

import sys,numpy
a = numpy.array([1.2,3.4])
print sys.getrefcount(a)

However, it turned out to be 2! So, if I:

del a

Will the "numpy.array([1.2,3.4])" object still be there (no garbage collection)?

解决方案

When you call getrefcount(), the reference is copied by value into the function's argument, temporarily bumping up the object's reference count. This is where the second reference comes from.

This is explained in the documentation:

The count returned is generally one higher than you might expect, because it includes the (temporary) reference as an argument to getrefcount().

As to your second question:

If I "del a", will the "numpy.array([1.2,3.4])" object still be there (no garbage collection)?

By the time getrefcount() exits, the array's reference count will to back to 1, and a subsequent del a would release the memory.

这篇关于为什么sys.getrefcount()返回2?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆