繁体   English   中英

如何计算Python 3.6中函数的调用次数?

[英]How do I count the number of calls of a function in Python 3.6?

我想计算inc内部的函数f的调用次数。 我应该如何修改main函数呢?

我有以下代码:

def inc(f):
    f()
    f()

def main():
    a = 0
    def f():
        a += 1
    inc(f)
    print(a)  # should print 2

main()

但这会导致错误:

Traceback (most recent call last):
  File "main.py", line 11, in <module>
    main()
  File "main.py", line 9, in main
    inc(f)
  File "main.py", line 2, in inc
    f()
  File "main.py", line 8, in f
    a += 1
UnboundLocalError: local variable 'a' referenced before assignment

通常的方法是为函数func创建一个属性func.invocations ,例如

def func(a):
    func.invocations += 1
    return a + 1

func.invocations = 0

并像这样使用

func(1)    # 2
func(10)   # 11
func.invocations  # 2

为了使整个事情更具可重用性和可读性,您还可以创建一个装饰器counter ,该counter可让您计算喜欢的任何函数的调用次数:

import functools

def counter(fn):
    @functools.wraps(fn)
    def helper(*args, **kargs):
        helper.invocations += 1
        return fn(*args, **kargs)
    helper.invocations = 0
    return helper

然后像

@counter
def func(a):
    return a + 1

func(1)    # 2
func(10)   # 11
func.invocations # 2
def inc(f):
    f()
    f()

def main():
    a = 0
    def f():
        nonlocal a
        a += 1
    inc(f)
    print(a)  # should print 2

main()

使F A外地()

如果您正在寻找一个简单的解决方案,则可以使用全局变量来解决问题。

reps = 0

def f():
    global reps 
    reps  += 1
    # do your func stuff here

f()
f()
f()
f()  # called f() 4 times
print(reps)  # -> 4

您可以尝试以下方法:

def inc(f):    
    f()    
    f() 


def main():    
    a = 0     
    def f():     
        f.counter += 1    
    f.counter =0    
    inc(f)     
    print(f.counter) 


main()

函数如何在python中成为对象,您可以创建一个属性来计算对该函数的调用次数

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM