Python对象引用计数为何比预期多1?技术问题求助
关于Python对象引用计数的疑问
我在测试Python对象的引用计数时遇到困惑,测试代码如下:
import sys class Square(): def __init__(self, width, color): self.width = width self.color = color oSquare1 = Square(5, 'red') print(oSquare1) # Reference count of the Square object should be 1 print ('Reference Count is ', sys.getrefcount(oSquare1)) oSquare2 = oSquare1 print(oSquare2) # Reference count of the Square object should be 2 print ('Reference Count is ', sys.getrefcount(oSquare1))
在Python2和Python3中运行该代码时,发现引用计数均比预期值多1:
$ python3 p.py <__main__.Square object at 0x7fea7f72ebe0> # reference should be 1 but the print statement says 2 Reference Count is 2 <__main__.Square object at 0x7fea7f72ebe0> # reference should be 2 but the print statement says 3 Reference Count is 3
想请教这一现象的原因,额外的引用计数来自何处?
原因解析
额外的引用计数完全来自sys.getrefcount()函数本身:
- 调用
sys.getrefcount(obj)时,函数会将传入的参数obj作为临时引用持有,直到函数执行结束才释放这个引用。 - 因此打印出的引用计数,会比你代码中实际存在的用户层引用数多1——这个额外的1就是函数调用过程中产生的临时参数引用。
如果要验证这一点,可以用gc.get_referrers()查看对象的引用来源,能清晰看到getrefcount调用时产生的临时引用记录。
内容的提问来源于stack exchange,提问作者Classified
相关产品推荐
相关产品推荐

