Skip to main content
 首页 » 编程设计

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

2024年11月24日9Free-Thinker

我想知道如何在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 


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

请您参考如下方法:

因为1000内部初始化的main和1000内部初始化的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实际上是不同的对象,因此ref的数量也不同。

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


  
  创建一个PyObject
  将PyObject的类型代码设置为整数
  将PyObject的值设置为 1000
  创建一个名为 a的名称
  将 a指向新的PyObject
  将PyObject的引用计数增加 1