You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python装饰器实现:如何用全局字典统一统计多函数调用次数?

解决Python装饰器统一统计函数调用次数的问题

要实现所有被装饰函数的调用次数统一存储到一个字典里,核心是让所有装饰后的函数共享同一个计数字典,而非每个函数对应独立的字典。下面是两种简洁的解决方案:

方法一:使用全局共享字典

直接定义一个全局字典,所有被装饰函数调用时都更新这个字典:

import datetime
import random

# 全局共享的调用计数字典
call_counts = {}

def count(func):
    def inner():
        func_name = func.__name__
        # 安全更新计数:存在则+1,不存在则初始化为1
        call_counts[func_name] = call_counts.get(func_name, 0) + 1
        func()
        print(f'当前调用状态:{call_counts}')
    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()

方法二:使用装饰器函数的属性存储字典

如果不想用全局变量,可以把字典绑定到装饰器函数自身的属性上,同样能实现共享:

import datetime
import random

def count(func):
    # 初始化共享字典,仅在第一次装饰函数时创建
    if not hasattr(count, 'call_counts'):
        count.call_counts = {}
    
    def inner():
        func_name = func.__name__
        count.call_counts[func_name] = count.call_counts.get(func_name, 0) + 1
        func()
        print(f'当前调用状态:{count.call_counts}')
    return inner

# 被装饰函数部分与方法一完全一致,此处省略

原代码问题分析

你之前的代码中,每个被装饰函数对应的inner闭包都有独立的dict属性,导致每个函数的调用次数被存储在各自的字典里,无法统一。上面两种方法通过让所有inner函数访问同一个字典,彻底解决了这个问题。

内容的提问来源于stack exchange,提问作者Kokopas

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.24 22:47:40