search

Home  >  Q&A  >  body text

python 为什么调用函数会令引用计数+2

import sys
a = 11
init_cnt = sys.getrefcount(a) - 1

print "init", init_cnt
####init 22
def function(c):
    print 'in function, count: ', sys.getrefcount(c) - 1
    ####in function, count:  24
    print '函数调用,计数器增加', sys.getrefcount(c) - 1 - init_cnt
    ####函数调用,计数器增加 2
function(a)

黄舟黄舟2787 days ago593

reply all(1)I'll reply

  • 天蓬老师

    天蓬老师2017-04-18 10:34:22

    After passing a as a parameter to function, it is referenced twice:

    for attr in dir(function):
        print attr, getattr(function, attr)
    

    You can see that parameter a is referenced by two attributes in the function object.

    reply
    0
  • Cancelreply