Python实现partial改变方法默认参数
作者:shichen2014 时间:2022-10-30 20:23:33
在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
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
JS:firefox 兼容性问题
2009-08-01 16:20:00
如何把数据从SQL Server导出到Access或Excel中去?
2009-11-02 20:26:00
纯js实现瀑布流布局及ajax动态新增数据
2023-08-08 07:11:23
![](https://img.aspxhome.com/file/2023/8/56028_0s.jpg)
AJAX请求类下载
2007-08-23 08:33:00
一个css垂直水平居中布局,css效果
2008-11-03 11:40:00
PHP中trait的使用和同时引入多个trait时同名方法冲突的处理方法
2023-06-16 23:13:52
![](https://img.aspxhome.com/file/2023/7/55497_0s.png)
SQL语句操作主从关系表
2011-06-19 13:19:05
禁止使用 Firebug
2009-05-20 12:04:00
PHP获取url的函数代码
2023-10-15 12:45:00
JS实现合并json对象的方法
2023-08-29 15:09:30
![](https://img.aspxhome.com/file/2023/2/56132_0s.jpg)
Javascript将数值转换为金额格式(分隔千分位和自动增加小数点)
2023-08-18 10:31:11
不要犯WEB字体编辑的10种错误
2008-08-19 12:55:00
![](https://img.aspxhome.com/file/UploadPic/20088/19/200881912588627s.gif)
python上下文管理器协议的实现
2023-08-28 18:32:18
Jupyter Notebook读取csv文件出现的问题及解决
2023-08-09 23:11:50
![](https://img.aspxhome.com/file/2023/9/64649_0s.jpg)
高效地获取XMLhttp对象
2010-01-19 13:49:00
纯CSS无限级下拉菜单
2009-09-17 11:29:00
asp如何编写一个DNS LOOKUP程序?
2009-11-07 18:47:00
如何使用Python抓取网页tag操作
2023-11-11 12:15:24
一个输入框提示列表效果
2008-03-09 18:53:00
JavaScript性能优化--创建文档碎片
2009-12-04 12:41:00