Python学习笔记(12)装饰器
Posted thyh
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Python学习笔记(12)装饰器相关的知识,希望对你有一定的参考价值。
import time
def show_time(f):
def inner(a, b):
start = time.time()
f(a, b)
end = time.time()
print(‘spend %s‘ % (end - start))
return inner
@show_time # add = show_time(add)
def add(a, b):
print(a + b)
time.sleep(1)
add(3, 4)
import time
import functools
def log(func):
@functools.wraps(func)
def wapper():
print(‘%s‘ % func.__name__)
func()
return wapper
@log
def now():
print(time.strftime(‘%Y-%m-%d %H:%M:%S‘, time.localtime()))
2018-04-27 21:56:56
now
functools.wraps 相当于写 wapper.__name__ = now.__name__
不然结果会成为
import time
import functools
def log(func):
# @functools.wraps(func)
def wapper():
print(‘%s‘ % func.__name__)
func()
return wapper
@log
def now():
print(time.strftime(‘%Y-%m-%d %H:%M:%S‘, time.localtime()))
now()
print(now.__name__)
2018-04-27 21:58:32
wapper
装饰器传递参数 如下例
import functools
import time
def log(text):
def decorator(func):
functools.wraps(func)
def wrapper():
print(‘%s-%s‘ % (text, func.__name__))
func()
return wrapper
return decorator
@log(‘whn‘) #now = log(‘xxx‘)(now)
def now():
print(time.strftime(‘%Y-%m-%d %H:%M:%S‘, time.localtime()))
now()
whn-now
2018-04-27 22:07:48
以上是关于Python学习笔记(12)装饰器的主要内容,如果未能解决你的问题,请参考以下文章