本文总结分析了Python装饰器简单用法。分享给大家供大家参考,具体如下:
装饰器在python中扮演着很重要的作用,例如插入日志等,装饰器可以为添加额外的功能同时又不影响业务函数的功能。
比如,运行业务函数fun()
同时打印运行花费的时间
1. 运行业务函数fun()
同时打印运行花费的时间
1
2
3
4
5
6
7
8
9
10
|
import time
def dec(fun):
start = time.time()
fun()
end = time.time()
a = end - start
print a
def myfun():
print 'run myfunction'
dec(myfun)
|
运行结果
(virt2) root@ubuntu:/home/z# python z.py
run myfunction
0.00108599662781
但是每次运行myfun都要调用dec,下面作下变动解决这个问题
2.
1
2
3
4
5
6
7
8
9
10
11
12
13
|
import time
def dec(fun):
def wrap():
start = time.time()
fun()
end = time.time()
a = end - start
print a
return wrap
def myfun():
print 'run myfunction'
myfun = dec(myfun)
myfun()
|
运行结果:
(virt2) root@ubuntu:/home/z# python z.py
run myfunction
0.00122618675232
这个装饰器dec就实现了,并且不影响函数myfun功能
3. 装饰器@符
1
2
3
4
5
6
7
8
9
10
11
12
13
|
import time
def dec(fun):
def wrap():
start = time.time()
fun()
end = time.time()
a = end - start
print a
return wrap
@dec
def myfun():
print 'run myfunction'
myfun()
|
结果
(virt2) root@ubuntu:/home/z# python z.py
run myfunction
0.000470876693726
使用了@后,就不用给myfun重新赋值了
@dec
就相当于myfun=dec(myfun)
例子:
1
2
3
4
5
6
7
8
9
10
11
|
def level(leveel):
def debug(func):
def wrapper( * args, * * kwargs):
print ( "[DEBUG]: enter {}()" . format (func.__name__),leveel)
return func( * args, * * kwargs)
return wrapper
return debug
@level (leveel = 'debuging' )
def say(something):
print ( "hello {}!" . format (something))
say( 123 )
|
输出:
('[DEBUG]: enter say()', 'debuging')
hello 123!
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
|
'''
class logging(object):
def __init__(self, func):
self.func = func
def __call__(self, *args, **kwargs):
print ("[DEBUG]: enter function {func}()".format(
func=self.func.__name__))
return self.func(*args, **kwargs)
@logging
def say(something):
print ("say {}!".format(something))
'''
class logging( object ):
def __init__( self , level = 'INFO' ):
self .level = level
def __call__( self , func): # 接受函数
def wrapper( * args, * * kwargs):
print ( "[{level}]: enter function {func}()" . format (
level = self .level,
func = func.__name__))
func( * args, * * kwargs)
return wrapper #返回函数
@logging (level = 'INFO' )
def say(something):
print ( "say {}!" . format (something))
say( 123 )
|
输出:
[INFO]: enter function say()
say 123!
希望本文所述对大家Python程序设计有所帮助。
原文链接:https://blog.csdn.net/darkfour/article/details/74747768