python内都是对象,变量都是对象的引用,这有点像C语言的指针。sys模块实际上是指python这个系统,sys.getrefcount接口可以查询对象的引用计数。
getrefcount(object, /)
Return the reference count of object.
The count returned is generally one higher than you might expect,
because it includes the (temporary) reference as an argument to
getrefcount().
sys.getrefcount返回的计数,总是比实际多1,因为包含了调用此函数的临时计数。
>>> import sys
>>> a = 1
>>> sys.getrefcount(a)
1080
>>> b = a
>>> sys.getrefcount(a)
1081
>>> c = [1,2,3]
>>> sys.getrefcount(c)
2
>>> d = c
>>> sys.getrefcount(c)
3
>>> del d
>>> sys.getrefcount(c)
2
1的引用计数好多,python系统内部很多地方都在使用1。
del语句会让引用计数减少。
默认在对应引用计数为0的时候,python内部的垃圾回收机制会将此对象所占用的内存收回。
-- EOF --