python装饰器的作用,我是这么理解的,
比如本来已经有几个写好的函数,这几个函数的返回值都是list,现在我想要它们都返回str型的值,一个个改函数太累,也容易出错,装饰器能解决这样的问题,它能对n个函数进行编程
def square(func): #返回平方 def _deco(a, b): rtn = func(a, b) return rtn * rtn return _deco @square def my_add(a, b): return a+b print my_add(1,2)
# 原来的几个返回list的函数,具体干嘛不管,示例用 def even_element(lst): return [n for n in lst if n%2 == 0] def odd_element(lst): return [n for n in lst if n%2 == 1] def link_list(lst1, lst2): l = deepcopy(lst1) l.extend(lst2) return l a = range(5) b = range(10) print even_element(a) print odd_element(a) print link_list(a, b)
from copy import deepcopy # 用装饰器 def list_to_str(func): def wrapper(*args, **kwargs): rtn_lst = [str(n) for n in func(*args, **kwargs)] return ','.join(rtn_lst) return wrapper # 此时这些函数都返回str型 @list_to_str def even_element(lst): return [n for n in lst if n%2 == 0] @list_to_str def odd_element(lst): return [n for n in lst if n%2 == 1] @list_to_str def link_list(lst1, lst2): l = deepcopy(lst1) l.extend(lst2) return l a = range(5) b = range(10) print even_element(a) print odd_element(a) print link_list(a, b)
带参数的装饰器
# encoding: utf-8 import time ''' 现实函数运行时间 参数run_times为被测函数运行次数 ''' def time_func(run_times): def _time_func(func): def wrapper(*args, **kwargs): t1 = time.time() for n in xrange(run_times): rtn = func(*args, **kwargs) t2 = time.time() print t2 - t1 return rtn return wrapper return _time_func @time_func(10000) def addd(a, b): return a+b print addd(1,2)