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程序设计有一定的借鉴与帮助价值。

相关文章

python 遍历pd.Series的index和value

遍历pd.Series的index和value的方法如下,python built-in list的enumerate方法不管用 for i, v in s.items(): p...

Python实现的ini文件操作类分享

类代码: # -*- coding:gbk -*- import ConfigParser, os class INIFILE: def __init__(self, filen...

python在TXT文件中按照某一字符串取出该字符串所在的行方法

主要流程:读取文件数据——将每一行数据分成不同的字符段——在判断 在某个字否段是否含与某个字符。(只是其中一种办法) 代码如下: with open(r"C:\Users\LENOV...

python 中文字符串的处理实现代码

>>> teststr = '我的eclipse不能正确的解码gbk码!' >>> teststr '\xe6\x88\x91\xe7\x9a\x84...

Win下PyInstaller 安装和使用教程

Win下PyInstaller 安装和使用教程

简介: PyInstaller可以将Python源代码发布成Win/MacOS等系统中的可执行文件。对开发者而言隐藏了源码实现,保护了知识产权。对使用者而言不用装环境,傻瓜式的双击就可以...