MST

星途 面试题库

面试题:Python装饰器中如何传递参数

请编写一个带有参数的Python装饰器,该装饰器用于记录被装饰函数的执行次数,并在每次调用时打印当前执行次数。要求给出完整的代码实现。
14.5万 热度难度
编程语言Python

知识考点

AI 面试

面试题答案

一键面试
def execution_counter(func):
    execution_count = 0
    def wrapper(*args, **kwargs):
        nonlocal execution_count
        execution_count += 1
        print(f"函数 {func.__name__} 执行次数: {execution_count}")
        return func(*args, **kwargs)
    return wrapper


@execution_counter
def test_function():
    pass


test_function()
test_function()
test_function()