计数器
您正在开发一个新的 Web 应用,想了解其中每个函数被调用了多少次。于是,您决定编写一个装饰器,为每个被装饰的函数添加一个计数器。将来,您可以利用这些信息判断是否有代码段已经不再被应用使用,从而可以删除。
本练习是课程的一部分
Python 函数编写
练习说明
- 调用被装饰的函数并返回结果。
- 返回新的装饰后函数。
- 使用
counter()装饰器装饰foo()。
交互式实操练习
通过完成这段示例代码来试试这个练习。
def counter(func):
def wrapper(*args, **kwargs):
wrapper.count += 1
# Call the function being decorated and return the result
return ____
# Set count to 0 to initialize call count for each new decorated function
wrapper.count = 0
# Return the new decorated function
____
# Decorate foo() with the counter() decorator
____
def foo():
print('calling foo()')
foo()
foo()
print('foo() was called {} times.'.format(foo.count))