python - “函数参数”的引用计数与“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
吗?有人可以详细解释一下吗?非常感谢!
解决方案
- foo 是指向该空列表的一个引用指针
- bar(foo)--> 这里 foo 是另一个引用同一个空列表的变量
- def bar(a) --> 这里 a 是另一个引用同一个空列表的变量
- Inside bar 函数,sys.getrefcount(a) --> 创建一个对同一个空列表的临时引用
- 因此总共是 4
推荐阅读
- laravel - Laravel Valet 共享错误:“dial tcp [...] no such host”
- php - spl_autoload_register 如何在内部工作
- javascript - 未捕获的类型错误:无法读取 select2 中 null 的属性“替换”
- android - 如何使用 bitbucket-pipelines 定位 apk 文件?
- c# - 当实体在不同的项目中时,为什么 Mediatr 不解析方法?
- excel - 兰德给出#n/a
- python - 如何在读取之前清除字符串并将str转换为int
- ios - Healthkit per hour 包含步数、距离和卡路里的活动摘要?
- javascript - 在显示从 0 到 100 % 的进度时,如何仅在数字符合某些标准时才显示它?
- parameters - 如何在空手道请求的字段中参数化部分字符串