首页 > 代码库 > python装饰器

python装饰器

Python装饰器定义:

 1 from functools import  wraps
 2 
 3 # 普通装饰器
 4 def decorator(func):
 5     @wraps(func)
 6     def wrap():
 7         print Doing somethings before executing func()
 8         func()
 9         print Doing somethings after executing func()
10 
11     return wrap
12 
13 
14 @decorator
15 def fun_test():
16     """
17     test
18     :return: 
19     """
20     print func
21 
22 fun_test()
23 
24 print fun_test.__name__
25 print fun_test.__doc__
26 
27 #result
28 # Doing somethings before executing func()
29 # func
30 # Doing somethings after executing func()
31 # fun_test
32 #
33 #     test
34 #     :return:

 

带入参装饰器

 1 from functools import  wraps
 2 
 3 # 带入参装饰器
 4 def loginfo(info):
 5 
 6     def loginfo_decorator(func):
 7         @wraps(func)
 8         def wrap_func(*args, **kwargs):
 9             print func.__name__ +  was called
10             print info:{info}.format(info=info)
11 
12             return func(*args, **kwargs)
13         return wrap_func
14     return loginfo_decorator
15 
16 @loginfo(test01)
17 def func1():
18     pass
19 
20 func1()
21 
22 # result
23 # func1 was called
24 # info:test01

 

装饰器类

 1 from functools import  wraps
 2 
 3 # 装饰器类
 4 
 5 class loginfo(object):
 6 
 7     def __init__(self, info=None):
 8         self.info = info
 9 
10     def __call__(self, func):
11         @wraps(func)
12         def wrap_func(*args, **kwargs):
13             print func.__name__ +  was called
14             print info:{info}.format(info=self.info)
15 
16             self.after()
17             return func(*args, **kwargs)
18         return wrap_func
19 
20     def after(self):
21         print after
22 
23 @loginfo(info=test02)
24 def func2():
25     pass
26 
27 func2()
28 
29 # result
30 # func2 was called
31 # info:test02
32 # after

 

python装饰器