本文实例讲述了Python装饰器用法。分享给大家供大家参考,具体如下:
无参数的装饰器
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
#coding=utf-8
def log(func):
def wrapper():
print 'before calling ' ,func.__name__
func()
print 'end calling ' ,func.__name__
return wrapper
@log
def hello():
print 'hello'
@log
def hello2(name):
print 'hello' ,name
if __name__ = = '__main__' :
hello()
|
运行结果:
before calling hello
hello
end calling hello
带参数的装饰器:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
#coding=utf-8
def log(func):
def wrapper(name):
print 'before calling ' ,func.__name__
func(name)
print 'end calling ' ,func.__name__
return wrapper
@log
def hello(name):
print 'hello' ,name
@log
def hello2(name):
print 'hello' ,name
if __name__ = = '__main__' :
hello( 'haha' )
|
运行结果:
before calling hello
hello haha
end calling hello
多个参数的时候:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
|
#coding=utf-8
def log(func):
'''
*无名字的参数
**有名字的参数
:param func:
:return:
'''
def wrapper( * args, * * kvargs):
print 'before calling ' ,func.__name__
print 'args' ,args, 'kvargs' ,kvargs
func( * args, * * kvargs)
print 'end calling ' ,func.__name__
return wrapper
@log
def hello(name,age):
print 'hello' ,name,age
@log
def hello2(name):
print 'hello' ,name
if __name__ = = '__main__' :
hello( 'haha' , 2 )
hello(name = 'hehe' ,age = 3 )
|
输出:
end calling hello
before calling hello
args () kvargs {'age': 3, 'name': 'hehe'}
hello hehe 3
end calling hello
装饰器里带参数的情况
本质就是嵌套函数
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
#coding=utf-8
def log(level, * args, * * kvargs):
def inner(func):
def wrapper( * args, * * kvargs):
print level, 'before calling ' ,func.__name__
print level, 'args' ,args, 'kvargs' ,kvargs
func( * args, * * kvargs)
print level, 'end calling ' ,func.__name__
return wrapper
return inner
@log (level = 'INFO' )
def hello(name,age):
print 'hello' ,name,age
@log
def hello2(name):
print 'hello' ,name
if __name__ = = '__main__' :
hello( 'haha' , 2 )
|
运行输出:
INFO before calling hello
INFO args ('haha', 2) kvargs {}
hello haha 2
INFO end calling hello
希望本文所述对大家Python程序设计有所帮助。
原文链接:https://blog.csdn.net/YANG_Gang2017/article/details/78568411