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 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163
| 1. 普通函数 def add(x,y): return x + y
2. 加强功能 def add(x,y): print("call add,x+y") return x + y
3. 业务分离 def add(x,y): return ...
def logger(fn,*args,**kwargs): ... x = fn(*args,**kwargs) ... return x
4. 柯里化 def add(x,y): return ...
def logger(fn): def wrapper(*args,**kwargs): ... x = fn(*args,**kwargs) ... return x return wrapper
print(logger(add)(5,y=50))
add = logger(add) print(add(x=5,y=10))
5. 装饰器语法糖 def logger(fn): def wrapper(*args,**kwargs): ... x = fn(*args,**kwargs) ... return x return wrapper @logger def add(x,y): return ...
6. 带参装饰器
def copy_properties(src): def _copy(dst): ... return dst return _copy
def logger(duration): @copy_properties(fn) def wrapper(*args,**kwargs): ...
7. 多参数装饰器 def logger(t1,t2): def _logger(fn): def wrap(*args,**kwargs): start = datetime.datetime.now() ret = fn(*args,**kwargs) duration = (datetime.datetime.now() - start).total_seconds() if duration > t1 and duration < t2: print("function {} took {}s.".format(fn.__name__,duration)) return ret return wrap return _logger
@logger(3,5) def add(x,y): 8. functools模块
- update_wrapper函数 import functools def logger(fn): @copy_properties(fn) def _logger(*args,**kwargs): '''This is a wrapper''' print('before') ret = fn(*args,**kwargs) print('after') return ret functools.update_wrapper(_logger,fn) print("{} {}".format(id(_logger),id(fn))) return _logger
@logger def add1(x,y): 'This is a function' ret = x + y return ret
print(add1.__name__,add1.__doc__,add1.__qualname__,sep='\n') print('*'*40) print(id(add1.__wrapped__))
输出: 139975566907728 139975566908408 add1 This is a function add1 **************************************** 139975566908408
- wraps函数
import functools def logger(fn): @functools.wraps(fn) def _logger(*args,**kwargs): '''This is a wrapper''' print('before') ret = fn(*args,**kwargs) print('after') return ret
print("{} {}".format(id(_logger),id(fn))) return _logger
@logger def add1(x,y): 'This is a function' ret = x + y return ret
print(add1.__name__,add1.__doc__,add1.__qualname__,sep='\n') print('*'*40) print(id(add1.__wrapped__)) print('@'*40) print(add1.__wrapped__(4,90))
输出: 139975561244184 139975561244048 add1 This is a function add1 **************************************** 139975561244048 @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ 94
|