Python中使用partial改变方法默认参数实例

yipeiwu_com5年前Python基础

Python 标准库中 functools库中有很多对方法很有有操作的封装,partial Objects就是其中之一,他是对方法参数默认值的修改。
下面就看下简单的应用测试。

复制代码 代码如下:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
#python2.7x
#partial.py
#authror: orangleliu

'''
functools 中Partial可以用来改变一个方法默认参数
1 改变原有默认值参数的默认值
2 给原来没有默认值的参数增加默认值
'''
def foo(a,b=0) :
    '''
    int add'
    '''
    print a + b

#user default argument
foo(1)

#change default argument once
foo(1,1)

#change function's default argument, and you can use the function with new argument
import functools

foo1 = functools.partial(foo, b=5)  #change "b" default argument
foo1(1)

foo2 = functools.partial(foo, a=10) #give "a" default argument
foo2()

'''
foo2 is a partial object,it only has three read-only attributes
i will list them
'''
print foo2.func
print foo2.args
print foo2.keywords
print dir(foo2)

##默认情况下partial对象是没有 __name__ __doc__ 属性,使用update_wrapper 从原始方法中添加属性到partial 对象中
print foo2.__doc__
'''
执行结果:
partial(func, *args, **keywords) - new function with partial application
    of the given arguments and keywords.
'''

functools.update_wrapper(foo2, foo)
print foo2.__doc__
'''
修改为foo的文档信息了
'''

相关文章

python登录WeChat 实现自动回复实例详解

python登录WeChat 实现自动回复实例详解

最近实现了一些微信的简单玩法 我们可以通过网页版的微信微信网页版,扫码登录后去抓包爬取信息,还可以post去发送信息。 》》安装itchat这个库  &nb...

Python 单例设计模式用法实例分析

本文实例讲述了Python 单例设计模式用法。分享给大家供大家参考,具体如下: demo.py(单例): class MusicPlayer(object): # 类属性 记录对...

Python PIL图片添加字体的例子

Python PIL图片添加字体的例子

效果 左边原图,右面添加字体后保存的图。 代码 # -*- coding: utf-8 -*- import PIL.Image as Image import PIL.Image...

Python向日志输出中添加上下文信息

除了传递给日志记录函数的参数(如msg)外,有时候我们还想在日志输出中包含一些额外的上下文信息。比如,在一个网络应用中,可能希望在日志中记录客户端的特定信息,如:远程客户端的IP地址和用...

Python中的引用和拷贝浅析

If an object's value can be modified, the object is said to be mutable. If the value cannot b...