functools学习记录

装饰器demo

def wrapper(func):
print('装饰器工作了')
def inner(*args,**kwargs):
return func(*args,**kwargs)
return inner @wrapper
def index():
print('index') @wrapper
def order():
print('order') print(index.__name__)
print(order.__name__) # 结果
装饰器工作了
装饰器工作了
inner
inner

functools.wraps

import functools

def wrapper(func):
print('装饰器工作了')
@functools.wraps(func) # 能够保留被装饰函数的元信息
def inner(*args,**kwargs):
return func(*args,**kwargs)
return inner @wrapper
def index():
print('index') @wrapper
def order():
print('order') print(index.__name__)
print(order.__name__) # 结果
装饰器工作了
装饰器工作了
index
order

functools.partial

偏函数:对函数进行封装,执行的时候自动传参数。

from functools import partial

def func(a,b,c):
return a+b+c f1 = partial(func,1)
v = f1(2,3)
print(v) # 6

偏函数应用

from functools import partial

class RequestContext():
def __init__(self):
self.request = '__request__'
self.session = '__session__' obj = RequestContext() def get_data(name):
if hasattr(obj,name):
return getattr(obj,name)
else:
return None request_proxy = partial(get_data,'request')
session_proxy = partial(get_data,'session')
request = request_proxy()
session = session_proxy() print(request)
print(session)
上一篇:李航《统计学习方法》CH02


下一篇:Ubuntu上安装MySQL