python 装饰器详解

装饰器

装饰器其实就是一个闭包,把一个函数当做参数然后返回一个替代版函数

装饰器有2个特性:

一是可以把被装饰的函数替换成其他函数, 

二是可以在加载模块时候立即执行

def w1(func):

  def inner():

     # 验证1

    # 验证2

     # 验证3  

     func()

  return inner

@w1

def f1():

print('f1')

装饰器(decorator)功能

1. 引⼊⽇志

2. 函数执⾏时间统计

3. 执⾏函数前预备处理

4. 执⾏函数后清理功能

5. 权限校验等场景

6. 缓存 

 

上代码直观感受

#定义函数: 完成包裹数据
def makeBold(fn):
def wrapped():
return "<b>" + fn() + "</b>"
return wrapped

@makeBold
def test1():
return "hello world-1"
#定义函数: 完成包裹数据
def makeItalic(fn):
def wrapped():
return "<i>" + fn() + "</i>"
return wrapped

@makeItalic
def test2():
return "hello world-2"

@makeBold
@makeItalic
def test3():
return "hello world-3"

print(test1())
print(test2())
print(test3())

装饰器对无参函数进行装饰
from time import ctime, sleep
def timefun(func):
def wrappedfunc():
print("%s called at %s"%(func.__name__, ctime()))
func()
return wrappedfunc
@timefun
def foo():
print("I am foo")
foo()
sleep(2)
foo()

装饰器对有参函数进行装饰

from time import ctime, sleep

def timefun(func):

  def wrappedfunc(a, b):

    print("%s called at %s"%(func.__name__, ctime()))

    print(a, b)

     func(a, b)

   return wrappedfunc

@timefun

def foo(a, b):

   print(a+b)

foo(3,5)

sleep(2)

foo(2,4)

装饰器对不定长参数函数进行装饰

from time import ctime, sleep

def timefun(func):

  def wrappedfunc(*args, **kwargs):

    print("%s called at %s"%(func.__name__, ctime()))

     func(*args, **kwargs)

   return wrappedfunc

@timefun

def foo(a, b, c):

   print(a+b+c)

foo(3,5,7)

sleep(2)

foo(2,4,9)

装饰器对带有返回值的函数进行装饰

from time import ctime, sleep

def timefun(func):

  def wrappedfunc(*args, **kwargs):

    print("%s called at %s"%(func.__name__, ctime()))

     ret = func()

    return ret

   return wrappedfunc

@timefun

def foo():

  print("I am foo")

@timefun 

def getInfo():

return '----hahah---'

 

带有参数的装饰器

from time import ctime, sleep

def timefun_arg(pre="hello"):

  def timefun(func):

  def wrappedfunc():

    print("%s called at %s %s"%(func.__name__, ctime(), pre))

     return func()

    return wrappedfunc

  return timefun

@timefun_arg(“sxt")

def foo():

  print("I am foo")

@timefun_arg("python")

def too():

  print("I am too" )

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

from time import ctime, sleep def timefun(func):     def wrappedfunc(*args, **kwargs):         print("%s called at %s"%(func.__name__, ctime()))         func(*args, **kwargs)     return wrappedfunc @timefun def foo(a, b, c):     print(a+b+c) foo(3,5,7) sleep(2) foo(2,4,9) 

posted @ 2019-03-24 18:11  一念之间的抉择  阅读(239)  评论(0编辑  收藏  举报