Thu*_*nix 6 python reference python-3.x
我想知道为什么打印此代码4而不是3。第四参考在哪里?
import sys
def f(a):
print(sys.getrefcount(a))
a = [1, 2, 3]
f(a)
Run Code Online (Sandbox Code Playgroud)
我们可以分步骤理解这一点:
import sys
print(sys.getrefcount([1, 2, 3]))
# output: 1
Run Code Online (Sandbox Code Playgroud)
import sys
a = [1, 2, 3]
print(sys.getrefcount(a))
# output: 2
Run Code Online (Sandbox Code Playgroud)
import sys
def f(a):
print(sys.getrefcount(a))
f([1, 2, 3])
# output: 3
Run Code Online (Sandbox Code Playgroud)
import sys
def f(a):
print(sys.getrefcount(a))
a = [1, 2, 3]
f(a)
# output: 4
Run Code Online (Sandbox Code Playgroud)
所以重申一下:
af函数的参数f第三个参考是需要的参数getrefcount函数的参数从参数 take 来看,没有第五个引用的原因getrefcount是它是在 C 中实现的,并且它们不会以相同的方式增加引用计数。第一个例子证明了这一点,因为其中的计数只有 1。