python partial_Python 偏函数 partial

偏函数是通过将一个函数的部分参数预先绑定为某些值,从而得到一个新的具有较少可变参数的函数。

Reproduce from

在 Python 中,可以通过 functools 中的 partial 高阶函数来实现偏函数功能。

实例

通过一下例子来看偏函数怎么使用,能够做什么。

实例一

有这样的逻辑判断需求;

for text in lines:

if re.search('[a-zA-Z]\=', text):

some_action(text)

elif re.search('[a-zA-Z]\s\=', text):

some_other_action(text)

else:

some_default_action(text)

这样写刚开始没问题,但是时间一长,可能就忘了这些正则表达式究竟是干什么的了。

重构后:

def is_grouped_together(text):

return re.search('[a-zA-Z]\=', text):

def is_spaced_apart(text):

return re.search('[a-zA-Z]\s\=', text)

for text in lines:

if is_grouped_together(text):

some_action(text)

elif is_spaced_apart(text):

some_other_action(text)

else:

some_default_action(text)

将内部的判断转换为函数来做判断(单一原则?);有合理性。

但是如果有更多类似的用于判断字符串模式的函数,那么就需要一个地方把它们统一管理起来:

from functools import partial

def my_search_method():

is_grouped_together = partial(re.search, '[a-zA-Z]\=')

is_spaced_apart = partial(re.search, '[a-zA-Z]\s\=')

for text in lines:

if is_grouped_together(text):

some_action(text)

elif is_spaced_apart(text):

some_other_action(text)

else:

some_default_action(text)

在这段代码中,我们通过functools.partial将re.search函数与不同的正则表达式绑定,从而得到了一系列供我们使用的专属函数。通过这种方法,不但使得代码更加简练,而且提高了可读性。

实例二

用 partial 生成具有继承关系的辅助对象。

假设我们要写一段处理 ajax 请求的代码,重构前代码:

def do_complicated_thing(request, slug):

if not request.is_ajax() or not request.method == 'POST':

return HttpResponse(json.dumps({'error': 'Invalid Request'}), content_type='application/json', status=400)

if not _has_required_params(request):

return HttpResponse(json.dumps({'error': 'Missing required param(s): {0}'.format(_get_missing)(request)}), content_type='application/json', status=400)

try:

_object = Object.objects.get(slug=slug)

except Object.DoesNotExist:

return HttpResponse(json.dumps({'error': 'No Object matching x found'}), content_type='application/json', status=400)

else:

result = do_a_bunch_of_staff(_object)

if result:

HttpResponse(json.dumps({'success': 'successfully did thing'}), content_type='application/json', status=200)

else:

HttpResponse(json.dumps({'success': 'successfully created thing'}), content_type='application/json', status=201)

这段代码有以下几个问题:

每次构造 HttpResponse 对象时,都需要传入 application/json 作为参数

每次都需要调用 json.dumps()

重复出现的状态码

这使得这段代码看起来不够精炼,占用了较大篇幅但实际上没有做太多事情。

重构的第一步时抽象出一个 `JsonPresponse 对象来承载返回值;

JsonResponse = lambda content, *args, **kargs: HttpResponse(

json.dumps(content),

content_type='application/json',

*args, **kargs

)

def do_complicated_thing(request, slug):

if not request.is_ajax() or not request.method == 'POST':

return JsonResponse({'error': 'Invalid Request'}, status=400)

if not _has_required_params(request):

return JsonResponse({'error': 'Missing required param(s): {0}'.format(_get_missing)(request)}, status=400)

try:

_object = Object.objects.get(slug=slug)

except Object.DoesNotExist:

return JsonResponse({'error': 'No Object matching x found'}, status=400)

else:

result = do_a_bunch_of_staff(_object)

if result:

JsonResponse({'success': 'successfully did thing'}, status=200)

else:

JsonResponse({'success': 'successfully created thing'}, status=201)

所有返回HttpResponse的地方都被我们新引入的JsonResponse所替代。

接下来,通过functools.partial,我们可以对Response做进一步的抽象,生成一系列JsonResponse的“子类”:

JsonOKResponse = partial(JsonResponse, status=200)

JsonCreatedResponse = partial(JsonResponse, status=201)

JsonBadRequestResponse = partial(JsonResponse, status=400)

def do_complicated_thing(request, slug):

if not request.is_ajax() or not request.method == 'POST':

return JsonBadRequestResponse({'error': 'Invalid Request'})

if not _has_required_params(request):

return JsonBadRequestResponse({'error': 'Missing required param(s): {0}'.format(_get_missing)(request)})

try:

_object = Object.objects.get(slug=slug)

except Object.DoesNotExist:

return JsonBadRequestResponse({'error': 'No Object matching x found'})

else:

result = do_a_bunch_of_staff(_object)

if result:

JsonOKResponse({'success': 'successfully did thing'})

else:

JsonCreatedResponse({'success': 'successfully created thing'})

这样,我们最大限度地减少了冗余代码,使代码精炼易读。

偏函数

偏函数是 functools.partial() 函数,将原函数当作第一个参数传入,原函数的各个参数以此作为 partial() 函数后续的参数,除非使用关键字参数,例如 partial(JsonResponse, status=400)。partial(func, *args, **keywords), 偏函数可以接受 func, *args, **kwargs 这三个参数。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值