Python decorators count function call

后端 未结 4 975
长发绾君心
长发绾君心 2020-12-10 15:54

I\'m refreshing my memory about some python features that I didn\'t get yet, I\'m learning from this python tutorial and there\'s an example that I don\'t fully understand.

4条回答
  •  借酒劲吻你
    2020-12-10 16:50

    What I don't get here is why do we increment the calls of the function wrapper (helper.calls += 1) instead of the function calls itself, and why does it actually working?

    I think to make it a generically useful decorator. You could do this

    def succ(x):
        succ.calls += 1
        return x + 1
    
    if __name__ == '__main__':
        succ.calls = 0
        print(succ.calls)
        for i in range(10):
            print(succ(i))
        print(succ.calls)
    

    which works just fine, but you would need to put the .calls +=1 in every function you wanted to apply this too, and initialise to 0 before you ran any of them. If you had a whole bunch of functions you wanted to count this is definitely nicer. Plus it initialises them to 0 at definition, which is nice.

    As i understand it it works because it replaces the function succ with the helper function from within the decorator (which is redefined every time it decorates a function) so succ = helper and succ.calls = helper.calls. (although of course the name helper is only definied within the namespace of the decorator)

    Does that make sense?

提交回复
热议问题