MST
星途 面试题库

面试题:Python装饰器高级难度:实现带状态的装饰器

请实现一个Python装饰器,这个装饰器能够记录被装饰函数的调用次数,并将调用次数作为一个属性暴露出来。每次调用被装饰函数时,该属性的值要自动增加。同时,被装饰函数本身的功能不能受到影响。
33.7万 热度难度
编程语言Python

知识考点

AI 面试

面试题答案

一键面试
def call_count_decorator(func):
    def wrapper(*args, **kwargs):
        wrapper.call_count += 1
        return func(*args, **kwargs)
    wrapper.call_count = 0
    return wrapper


@call_count_decorator
def test_function():
    print("This is a test function.")


test_function()
test_function()
print(f"Function call count: {test_function.call_count}")