利用装饰器实现功能:在所有函数运行结束时输出“Game Over"和函数运行时间
时间: 2024-04-29 22:23:47 浏览: 14
以下是利用装饰器实现该功能的代码:
```python
import time
def game_over(func):
def wrapper(*args, **kwargs):
start_time = time.time()
result = func(*args, **kwargs)
end_time = time.time()
print("Game Over")
print("Function {} took {:.2f} seconds to run".format(func.__name__, end_time - start_time))
return result
return wrapper
@game_over
def my_function():
# function code here
pass
# Call the decorated function
my_function()
```
在这个例子中,`game_over`是一个装饰器函数,它接受一个函数作为参数,并返回一个新的函数`wrapper`。`wrapper`函数包装了原始函数,它首先记录函数开始运行时的时间,然后运行原始函数,并记录函数结束时间。最后,它打印出“Game Over”和函数运行时间,然后返回原始函数的结果。
使用`@game_over`语法将装饰器应用于函数。在调用`my_function`时,实际上是调用了`wrapper`函数,从而在函数运行结束时打印出了“Game Over”和运行时间。
注意,在使用装饰器时,原始函数的参数个数可能不同,因此使用`*args`和`**kwargs`来接受任意数量和类型的参数。