Python decorators count function call

后端 未结 4 978
长发绾君心
长发绾君心 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:34

    When you decorate a function you "substitute" you're function with the wrapper.

    In this example, after the decoration, when you call succ you are actually calling helper. So if you are counting calls you have to increase the helper calls.

    You can check that once you decorate a function the name is binded tho the wrapper by checking the attribute __name__ of the decorated function:

    def call_counter(func):
        def helper(*args, **args):
            helper.calls += 1
            return func(*args, **args)
        helper.calls = 0
        return helper
    
    @call_counter
    def succ(x):
        return x + 1
    
    succ(0)
    succ(1)
    print(succ.__name__)
    >>> 'helper'
    print(succ.calls)
    >>> 2
    

提交回复
热议问题