【问题标题】:How is the reference count from "function argument" different from that from "Python's function stack" - Python“函数参数”的引用计数与“Python 的函数堆栈”的引用计数有何不同 - Python
【发布时间】:2019-08-17 18:49:17
【问题描述】:

我正在尝试了解 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 一样吗?有人可以详细解释一下吗?非常感谢!

【问题讨论】:

    标签: python reference-counting


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

    【讨论】:

      猜你喜欢
      • 2012-04-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-11-25
      • 2022-01-20
      • 1970-01-01
      相关资源
      最近更新 更多