【函数式编程】Python3 有参数的装饰器:以显示函数执行时间为例

199 阅读2分钟

本文已参与「新人创作礼」活动,一起开启掘金创作之路

装饰器(Decorators)是 Python 的一个重要部分。简单地说:装饰器是一个高阶函数,用来修改其他函数的功能。他们有助于让我们的代码更简短,也更符合Python编程风格。本文将要分享一种接受参数的装饰器,并介绍哪些区域里装饰器可以让你的代码更简洁。

在Python中,函数和值都是对象,都可以和变量名动态绑定。我们可以在函数中定义另外的函数,即创建嵌套的函数。我们可以在一个函数里执行另一个函数。我们也可以从函数中返回函数,将其作为输出返回出来。还可以将函数作为参数,传给另一个函数。装饰器就是这样的一个函数,它们封装一个函数,并且用这样或者那样的方式来修改它的行为。

这是Python中使用装饰器的编程语法和使用规范:

 from functools import wraps
 def decorator_name(f):
     @wraps(f)
     def decorated(*args, **kwargs):
         if not can_run:
             return "Function will not run"
         return f(*args, **kwargs)
     return decorated
  
 @decorator_name
 def func():
     return("Function is running")
  
 can_run = True
 print(func())
 # Output: Function is running
  
 can_run = False
 print(func())
 # Output: Function will not run

本文介绍可以接受参数的装饰器,并以一个用来显示函数执行时间的装饰器为例。因为装饰器本身是一个函数,所以可以作为另一个函数的返回值。我们设计一个函数,接受参数,并返回对应的装饰器,从而实现装饰器的定制。

以下的代码用来装饰一个函数,使函数运行完毕后能显示函数的运行时间,而且可以自定义提示信息。

 def time_decorator_with_prompt(prompt_infor):
     def time_decorator(f):
         @wraps(f)
         def decorated(*args, **kwargs):
             start_time = time.time()
             result = f(*args, **kwargs)
             print(prompt_infor + ", Time =", time.time() - start_time)
             return result
         return decorated
     return time_decorator

这段代码最有意义的是给装饰器加参数。通过外面套一个函数的壳(time_decorator_with_prompt),使用多少参数都可以通过外面的壳传入,然后在壳内部直接使用这些参数确定装饰器,最后返回这个被确定的装饰器。在外部确定参数,也是函数式编程一个很大的应用。

以下是一个应用的例子:

 @time_decorator_with_prompt(prompt_infor = "Load File Successfully")
 def load_file():
     # load some file
     return something
 ​
 load_file()

输出信息:

 Load File Successfully, Time = 0.01

\