脚本之家,脚本语言编程技术及教程分享平台!
分类导航

Python|VBS|Ruby|Lua|perl|VBA|Golang|PowerShell|Erlang|autoit|Dos|bat|

服务器之家 - 脚本之家 - Python - python中的decorator的作用详解

python中的decorator的作用详解

2021-03-22 00:08丹华抱一鷇音子 Python

这篇文章主要介绍了python中的decorator的作用详解,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧

1、概念

装饰器(decorator)就是:定义了一个函数,想在运行时动态增加功能,又不想改动函数本身的代码。可以起到复用代码的功能,避免每个函数重复性编写代码,简言之就是拓展原来函数功能的一种函数。在python中,装饰器(decorator)分为 函数装饰器 和 类装饰器 两种。python中内置的@语言就是为了简化装饰器调用。

列出几个装饰器函数:

打印日志:@log

检测性能:@performance

数据库事务:@transaction

URL路由:@post('/register')

2、使用方法

(1)无参数decorator

编写一个@performance,它可以打印出函数调用的时间。

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
import time
 
def performance(f):
 def log_time(x):
  t1 = time.time()
  res = f(x)
  t2 = time.time()
  print 'call %s() in %fs' %(f.__name__,(t2 - t1))
  return res
 return log_time
 
@performance
def factorial(n):
 return reduce(lambda x,y : x*y,range(1,n+1))
 
print factorial(10)

运行结果:

call factorial() in 0.006009s 2 3628800

运行原理:

此时,factorial就作为performance的函数对象,传递给f。当调用factorial(10)的时候也就是调用log_time(10)函数,而在log_time函数内部,又调用了f,这就造成了装饰器的效果。说明f是被装饰函数,而x是被装饰函数的参数。

(2)带参数decorator

请给 @performace 增加一个参数,允许传入's'或'ms'。

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
import time
 
def performance(unit):
 def perf_decorator(f):
  def wrapper(*args, **kw):
   t1 = time.time()
   r = f(*args, **kw)
   t2 = time.time()
   t = (t2 - t1)*1000 if unit =='ms' else (t2 - t1)
   print 'call %s() in %f %s'%(f.__name__, t, unit)
   return r
  return wrapper
 return perf_decorator
 
@performance('ms')
def factorial(n):
 return reduce(lambda x,y: x*y, range(1, n+1))
 
print factorial(10)

运行结果:

call factorial() in 9.381056 ms 2 3628800

运行原理:

它的内部逻辑为factorial=performance('ms')(factorial);

这里面performance('ms')返回是perf_decorator函数对象,performance('ms')(factorial)其实就是perf_decorator(factorial),然后其余的就和上面是一样的道理了。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。

原文链接:http://www.cnblogs.com/cpl9412290130/p/9368821.html

延伸 · 阅读

精彩推荐