垃圾收集器如何跟踪python中的引用?

时间:2018-04-12 04:11:16

标签: python

使用数字分析(.+)?内置行为& string 我感到很困惑。

id()

现在我尝试将x = 100 y = x # x and y both points to same object that is 100 id(x) 162569156 id(y) 162569156 指向的对象更改为

x

现在,据我所知,python垃圾收集器是引用计数垃圾收集器,当前 x = 200 # since x points to different objects & garbage collector increments reference counts as its no longer points to old objects id(y) 162569156 id(x) # its different 162569932 或引用数量发生变化,清理它。 这是我的疑问,从上面我可以假设,每当我再次x=200,即试图指向旧对象时,x = 100将始终提供完全相同的内存位置?

id()

如果以上情况属实,那么这意味着对于每个数字(数百万),一个引用将在那里,而x = 100 #making x to points to same old object id(x) 162569156 #getting same old location id(y) 162569156 在指向旧对象相同位置 >将来?

一旦指针丢失了地址(堆),我就会像id()中的其他语言一样怀疑这个问题,但是当你执行C时,它不能保证下一次会得到相同的地址。

1 个答案:

答案 0 :(得分:-1)

对于小值python总是创建一个id并存储创建相同值时创建的id只是将id赋给变量

  

Python缓存[-5,256]范围内的整数,因此可以预期   该范围内的整数也是相同的。

In [1]: x=100

In [2]: y=100 #here x and y are diff but still same id

In [3]: id(x)
Out[3]: 10758048

In [4]: id(y)
Out[4]: 10758048

我只是想展示一些针对大型商标的演示

In [9]: x=1000

In [10]: x=y

In [11]: id(x)
Out[11]: 20359984

In [12]: id(y)
Out[12]: 20359984

In [13]: x=1001

In [14]: id(x)
Out[14]: 20360056

In [15]: x=1000 # again assigning to x to 1000

In [16]: id(x)
Out[16]: 19649168 # id got differs because python normally does not keep reference for large ints

Similar Question