当前位置: 首页 > 面试题库 >

“sys.getrefcount()” return value

宗政博
2023-03-14
问题内容

Why does

sys.getrefcount()

return 3 for every large number or simple string?Does that mean that 3 objects
reside somewhere in the Program?Also,why doesn’t setting x=(very large number)
increase that object’s ref count?Do those 3 ref counts result from my call to
getrefcount? Thank you for clarifying this.

for instance:

>>> sys.getrefcount(4234234555)
3
>>> sys.getrefcount("testing")
3
>>> sys.getrefcount(11111111111111111)
3
>>> x=11111111111111111
>>> sys.getrefcount(11111111111111111)
3

问题答案:

Large integer objects are not reused by the interpretor, so you get two
distinct objects:

>>> a = 11111
>>> b = 11111
>>> id(a)
40351656
>>> id(b)
40351704

sys.getrefcount(11111) always returns the same number because it measures the
reference count of a fresh object.

For small integers, Python always reuses the same object:

>>> sys.getrefcount(1)
73

Usually you would get only one reference to a new object:

>>> sys.getrefcount(object())
1

But integers are allocated in a special pre-malloced area by Python for
performance optimization, and I suspect the extra two references have
something to do with this.

You can look at the C implementation here:
http://svn.python.org/view/python/trunk/Objects/intobject.c?view=markup

Edit: I do not claim to understand what’s going on in lowlevel details, I
think there are several things at work that cache temporary references:

print sys.getrefcount('foo1111111111111' + 'bar1111111111111') #1
print sys.getrefcount(111111111111 + 2222222222222)            #2
print sys.getrefcount('foobar333333333333333333')              #3


 类似资料:
  • 问题内容: 据我了解,sys.getrefcount()返回对象的引用数,在以下情况下“应”为1: 但是,结果是2!所以,如果我: “ numpy.array([1.2,3.4])”对象是否仍然存在(没有垃圾回收)? 问题答案: 当您调用时,引用将按值复制到函数的参数中,从而临时增加了对象的引用计数。这是第二个引用来源。 在文档中对此进行了解释: 返回的计数通常比您预期的高一,因为它包含(临时)引

  • 使用aws/aws-sdk-php 3.21.6。我一定是误解了当条件表达式遇到条件检查失败异常错误时返回值是如何工作的。 我希望的是,如果ConditionExpression失败,进而触发ConditionalCheckFailedException,我可以捕获这个异常,然后通过ReturnValue从DD访问新属性。 我期望ReturnValue中的docs属性似乎暗示了这一点。 然而,通过

相关阅读

相关文章

相关问答