• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
孙龙 程序员
少时总觉为人易,华年方知立业难
博客园    首页    新随笔    联系   管理    订阅  订阅
partial函数 偏函数

   一个函数可以有多个参数,而在有的情况下有的参数先得到,有的参数需要在后面的情景中才能知道,python 给我们提供了partial函数用于携带部分参数生成一个新函数。

def add(a,b,c=2):
    print("a is:%s b is %s c is %s"%(a,b,c))
    return a+b+c
add_with_a_b=partial(add,2,3)
print(add_with_a_b())# it's 7
add_with_a=partial(add,9)
print(add_with_a(10))# it's 21
#################

a is:2 b is 3 c is 2
a is:9 b is 10 c is 2

下面一个列子是用partial来生成了一个装饰器,用于修改函数的__doc__为另一个函数的

#coding:utf-8
'''
Created on 2014-10-1
@author: zkchen
'''
from functools import partial
PARAMS=("__doc__",)
def update_params(target,source,params=PARAMS):
    #将target的在PARAMS中提到的属性设置为source的
    [setattr(target,p,getattr(source,p,None)) for p in PARAMS]
    return target
def update_params_wrap(source):
    return partial(update_params,source=source,params=PARAMS)

def test_partial():
    def funcA():
        '''this is funcA's doc'''
        pass
    @update_params_wrap(funcA)
    def funcB():
        '''this is funcB's doc'''
        pass
    print(funcB.__doc__)
#################################
this is funcA's doc

 

本文来自博客园,作者:孙龙-程序员,转载请注明原文链接:https://www.cnblogs.com/sunlong88/articles/9526153.html

posted on 2018-08-23 20:37  孙龙-程序员  阅读(123)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3