MST
星途 面试题库

面试题:Python函数装饰器复杂应用

编写一个带参数的函数装饰器,这个装饰器可以统计被装饰函数的调用次数,并在函数执行前打印当前调用次数。如果调用次数达到5次,打印一条特殊消息并停止函数的后续执行。例如,第一次调用函数前打印'Call 1',第五次调用函数前打印'Call 5, this is the last call',然后函数不再执行。
39.2万 热度难度
编程语言Python

知识考点

AI 面试

面试题答案

一键面试
def call_counter(func):
    call_count = 0
    def wrapper(*args, **kwargs):
        nonlocal call_count
        call_count += 1
        if call_count == 5:
            print(f"Call {call_count}, this is the last call")
            return
        print(f"Call {call_count}")
        return func(*args, **kwargs)
    return wrapper


@call_counter
def test_function():
    print("Function is running")


test_function()
test_function()
test_function()
test_function()
test_function()
test_function()