Python装饰器:计算函数调用次数

huangapple go评论60阅读模式
英文:

Python Decorator: Count Function Calls

问题

我想创建一个装饰器来计算函数调用次数。
我已经接近成功,但问题是每个函数都有一个单独的字典输出,我想要将每个函数存储在一个字典中。
如何创建一个全局字典来存储这样的数据?我尝试添加另一个创建字典的装饰器,但没有帮助,非局部变量也没有帮助?

def count(func):
    def inner():
        inner.calls += 1
        if inner.calls > 1:
            count_update = inner.dict[func.__name__] + 1
            update = {func.__name__:count_update}
            inner.dict.update(update)         
        else:     
            inner.dict={func.__name__:1}
        func()
        print(f'当前状态 {inner.dict}')           
    inner.calls = 0
    inner.dict={}
    return inner

@count
def show_date():
    current_time = datetime.now()
    current_time_formatted = current_time.strftime("%Y-%d-%B-%A")
    print(current_time_formatted)   
    return current_time_formatted

@count
def print_random_number2():
    numb = random.randint(0,10000)
    string_final=f'数字是 {numb}'
    print(string_final)
    return string_final

show_date()
show_date()
show_date()
print_random_number2()
print_random_number2()
show_date()
英文:

I want to create decorator that calculates funtion calls.
I am close but the problem is output is separate dictionary for every function, I want every function to be stored in one dictionary.
How to make global dictionary which can store such data, I tried adding another decorator that created dictionary but it did not help, nonlocal variable also did not help either?

def count(func):
    def inner():
        inner.calls += 1
        if inner.calls > 1:
            count_update = inner.dict[func.__name__] + 1
            update = {func.__name__:count_update}
            inner.dict.update(update)         
        else:     
            inner.dict={func.__name__:1}
        func()
        print(f'Current state {inner.dict}')           
    inner.calls = 0
    inner.dict={}
    return inner

@count
def show_date():
    current_time = datetime.now()
    current_time_formatted = current_time.strftime("%Y-%d-%B-%A")
    print(current_time_formatted)   
    return current_time_formatted

@count
def print_random_number2():
    numb = random.randint(0,10000)
    string_final=f'Number is {numb}'
    print(string_final)
    return string_final

show_date()
show_date()
show_date()
print_random_number2()
print_random_number2()
show_date()

答案1

得分: 1

你可以通过在全局范围内创建一个字典来声明全局字典(即在函数外部):

func_counts = {}
def count(func):
    def inner():
        func_counts[func.__name__] = func_counts.get(func.__name__, 0) + 1
        func()
        print(f'当前状态 {func_counts}')
    return inner

不需要使用 globalnonlocal 来声明它,因为你在函数内部没有重新绑定它。

英文:

You can declare a global dictionary by just creating a dictionary in the global scope (i.e. outside the function):

func_counts = {}
def count(func):
    def inner():
        func_counts[func.__name__] = func_counts.get(func.__name__, 0) + 1
        func()
        print(f'Current state {func_counts}')
    return inner

It's not necessary to declare it with global or nonlocal because you aren't rebinding it inside the function.

huangapple
  • 本文由 发表于 2023年4月17日 04:34:39
  • 转载请务必保留本文链接:https://go.coder-hub.com/76030190.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定