Counting python method calls within another method

后端 未结 3 1611
囚心锁ツ
囚心锁ツ 2020-11-29 10:11

I\'m actually trying doing this in Java, but I\'m in the process of teaching myself python and it made me wonder if there was an easy/clever way to do this with wrappers or

3条回答
  •  眼角桃花
    2020-11-29 10:54

    This defines a decorator to do it:

    def count_calls(fn):
        def _counting(*args, **kwargs):
            _counting.calls += 1
            return fn(*args, **kwargs)
        _counting.calls = 0
        return _counting
    
    @count_calls
    def foo(x):
        return x
    
    def bar(y):
        foo(y)
        foo(y)
    
    bar(1)
    print foo.calls
    

提交回复
热议问题