首页 > 编程语言 > 详细

python 装饰器详解

时间:2019-03-24 19:03:32      阅读:127      评论:0      收藏:0      [点我收藏+]

装饰器

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

装饰器有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) 

python 装饰器详解

原文:https://www.cnblogs.com/Minlwen/p/10589376.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!