【每天1分钟】PYTHON基础之函数(偏函数)
用法:
>>> from functools import partial
>>> help(partial)
Help on class partial in module functools:
class partial(builtins.object)
| partial(func, *args, **keywords) - new function with partial application
| of the given arguments and keywords.
|
| Methods defined here:
|
| __call__(self, /, *args, **kwargs)
| Call self as a function.
|
| __delattr__(self, name, /)
| Implement delattr(self, name).
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __new__(*args, **kwargs) from builtins.type
| Create and return a new object. See help(type) for accurate signature.
|
| __reduce__(...)
| helper for pickle
|
| __repr__(self, /)
| Return repr(self).
|
| __setattr__(self, name, value, /)
| Implement setattr(self, name, value).
|
| __setstate__(...)
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __dict__
|
| args
| tuple of arguments to future partial calls
|
| func
| function object to use in future partial calls
|
| keywords
| dictionary of keyword arguments to future partial calls
>>>
简单地说:
func 函数名称
args 传入原来函数的元组型参数
keywords 传入原来函数的字典型参数
举例:
>>> from functools import partial
>>>
>>> def myadd(arg1, arg2):
return arg1 + arg2
>>> addone = partial(myadd, arg2 = 1)
>>>
>>> addone(2)
3
>>> addtwo = partial(myadd, 2)
>>>
>>> addtwo(2)
4
>>>