首页 > 解决方案 > “函数参数”的引用计数与“Python 的函数堆栈”的引用计数有何不同 - Python

问题描述

我试图了解 Python 中的引用计数。这是我从帖子(https://rushter.com/blog/python-garbage-collector/)中得到的一个例子:

foo = []

# 2 references, 1 from the foo var and 1 from getrefcount
print(sys.getrefcount(foo))

def bar(a):
    # 4 references
    # from the foo var, function argument, getrefcount and Python's function stack
    print(sys.getrefcount(a))

bar(foo)
# 2 references, the function scope is destroyed
print(sys.getrefcount(foo))

我不清楚为什么第二个sys.getrefCount是 4。作者说这四个引用来自 foo var、函数参数、getrefcount 和 Python 的函数堆栈。调用的引用不是与bar(foo)相同Python's function stack吗?有人可以详细解释一下吗?非常感谢!

标签: pythonreference-counting

解决方案


  • foo 是指向该空列表的一个引用指针
  • bar(foo)--> 这里 foo 是另一个引用同一个空列表的变量
  • def bar(a) --> 这里 a 是另一个引用同一个空列表的变量
  • Inside bar 函数,sys.getrefcount(a) --> 创建一个对同一个空列表的临时引用
  • 因此总共是 4

推荐阅读