python 装饰器
Posted valorchang
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python 装饰器相关的知识,希望对你有一定的参考价值。
1.在执行目标函数前附加一些内容或者功能:
1
2
3
4
5
6
7
8
9
10
|
def demo(func): print ( ‘before exec %s ‘ % func.__name__) func() print ( ‘after exec %s ‘ % func.__name__) return func def func(): print ( ‘hello world‘ ) func = demo(func) func() |
2.使用语法糖@来装饰函数
1
2
3
4
5
6
7
8
9
|
def demo(func): print ( ‘before exec %s ‘ % func.__name__) func() print ( ‘after exec %s ‘ % func.__name__) return func @demo def func(): print ( ‘hello world‘ ) func() |
3.使用内嵌包装饰函数保证每次新函数都被调用
1
2
3
4
5
6
7
8
9
10
|
def demo(func): def inner(): print ( ‘before exec %s ‘ % func.__name__) func() print ( ‘after exec %s ‘ % func.__name__) return inner @demo def func(): print ( ‘hello world‘ ) func() |
4.对带参数的函数进行装饰
1
2
3
4
5
6
7
8
9
10
11
12
|
def demo(func): def inner(a,b): print ( ‘before exec %s ‘ % func.__name__) ret = func(a,b) print ( ‘after exec %s ‘ % func.__name__) return ret return inner @demo def func(a,b): print ( ‘hello world‘ ) return a + b print (func( 1 , 2 )) |
5.对参数数量不确定的函数进行装饰
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
def demo(func): def inner( * args, * * kwargs): print ( ‘before exec %s ‘ % func.__name__) ret = func( * args, * * kwargs) print ( ‘after exec %s ‘ % func.__name__) return ret return inner @demo def func(a,b): print ( ‘hello world func‘ ) return a + b @demo def func1(a,b,c): print ( ‘hello world func1‘ ) return a + b + c print (func( 1 , 2 )) print (func1( 1 , 2 , 3 )) |
6.装饰器带参数
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
def demo(arg): def warper(func): def inner( * args, * * kwargs): print ( ‘before exec %s %s‘ % (func.__name__,arg)) ret = func( * args, * * kwargs) print ( ‘after exec %s %s ‘ % (func.__name__,arg)) return ret return inner return warper @demo ( ‘qq‘ ) def func(a,b): print ( ‘hello world func‘ ) return a + b @demo ( ‘wechat‘ ) def func1(a,b,c): print ( ‘hello world func1‘ ) return a + b + c print (func( 1 , 2 )) print (func1( 1 , 2 , 3 )) |
7.多个装饰器装饰一个函数
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
def wrapper1(func): def inner(): print ( ‘wrapper1 ,before func‘ ) func() print ( ‘wrapper1 ,after func‘ ) return inner def wrapper2(func): def inner(): print ( ‘wrapper2 ,before func‘ ) func() print ( ‘wrapper2 ,after func‘ ) return inner @wrapper2 @wrapper1 def f(): print ( ‘in f‘ ) f() |
8.装饰器带类参数
9.装饰器带类参数,并分拆公共类到其他py文件中,同时演示了对一个函数应用多个装饰器
以上是关于python 装饰器的主要内容,如果未能解决你的问题,请参考以下文章