sys.getrefcount返回不同范围的非连续值

时间:2019-06-18 11:01:52

标签: python python-3.x

我想知道如何在python中分配内存。为此,我曾经在python上玩。但是我陷入了以下问题。

对于以下代码,如果我使用10而不是1000,则在函数中获得了预期的引用计数值

import sys
def show_ref_count(a):
    print("ref count of 1000 within function : ",sys.getrefcount(1000))
    print("adrs of a : ",id(a))

# main function
a = 1000
b = 1000
c = 1000
print("ref count of 1000 : ",sys.getrefcount(1000))
print("adrs of a : ",id(a))
show_ref_count(a)

代码的输出是

ref count of 1000 :  6
adrs of a :  140309334530448
ref count of 1000 within function :  3
adrs of a :  140309334530448

存储在内存loc中的整数1000:140309334530448,并且main和show_ref_count使用相同的地址。但是在show_ref_count函数中,1000的引用计数显示为3而不是7。为什么?

1 个答案:

答案 0 :(得分:1)

因为在1000内部初始化的main1000内部的show_ref_count是不同的对象。您可以在函数中添加一行

import sys
def show_ref_count(a):
    print("ref count of 1000 within a function: ", sys.getrefcount(1000))
    print("addr of var: ", id(a))
    print("addr of 1000 within function: ", id(1000))

# main function
a = 1000
b = 1000
c = 1000

print("ref count of 1000: ", sys.getrefcount(1000))
print("addr of a: ", id(a))
print("addr of 1000: ", id(1000))

show_ref_count(a)

并检查输出

ref count of 1000:  3
addr of a:  140646358917616
addr of 1000:  140646358918000

ref count of 1000 within a function:  2
addr of var:  140646358917616
addr of 1000 within function:  140646390098512

要弄清楚这两个1000实际上是不同的对象,因此引用的数量也不同。

注意:用a初始化的1000也不是同一对象,并且具有不同的地址(如果您查看上面的输出)。 It happens since variables in Python are not actually variables but rather 'names' of objects.从本文来看,总体过程如下:

  
      
  1. 创建一个PyObject

  2.   
  3. 将PyObject的类型代码设置为整数

  4.   
  5. 将PyObject的值设置为1000

  6.   
  7. 创建一个名为a

  8. 的名称   
  9. a指向新的PyObject

  10.   
  11. 通过1

  12. 增加PyObject的引用计数