装饰器函数
1、最简单的装饰器
import time
def timmer(f):
def inner():
start = time.time()
f()
end = time.time()
print(end - start)
return inner
def func():
time.sleep(0.01)
print('你好')
func = timmer(func)
func()
2、语法糖&有返回值的装饰器
import time
def timmer(f):
def inner():
start = time.time()
s = f()
print(time.time() - start)
return s
return inner
@timmer
def func():
time.sleep(0.01)
print('你好')
return 'hello world'
a = func()
print(a)
3、有一个参数的装饰器
import time
def timmer(f):
def inner(x):
start = time.time()
s = f(x)
print(time.time() - start, x)
return s
return inner
@timmer
def func(x):
time.sleep(0.01)
print('你好')
return 'hello world'
a = func(5)
print(a)
#返回值:
#你好
#0.010042667388916016 5
#hello world
4、wrapper模板
def wrapper(f):
def inner(*args, **kwargs):
'''在被装饰函数之前要做的事'''
s = f(*args, **kwargs)
'''在被装饰函数之后要做的事'''
return s
return inner
@wrapper
def func():
print('你好')
return'hello word'
a = func()
print(a)
#返回:
#你好
#hello word
相关练习
1.编写下载网页内容的函数,要求功能是:用户传入一个url,函数返回下载页面的结果
2.为题目1编写装饰器,实现缓存网页内容的功能:
具体:实现下载的页面存放于文件中,如果文件内有值(文件大小不为0),就优先从文件中读取网页内容,否则,就去下载,然后存到文件中
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
import os from urllib.request import urlopen def cache(func): def inner(*args, **kwargs): if os.path.getsize('web_cache'): with open('web_cache', 'rb') as f: return f.read() ret = func(*args, **kwargs) with open('web_cache', 'wb') as f: f.write(ret) return ret return inner @cache def get(url): code = urlopen(url).read() return code a = get('http://www.baidu.com') print(a)