我已经知道的
我们知道可以这样来用partial
import functools
int2 = functools.partial(int, base=2)
print(int2('10001'))
# Output: '17'
int 函数的解释如下:
class int(object)
| int(x=0) -> integer
| int(x, base=10) -> integer
|
| Convert a number or string to an integer, or return 0 if no arguments
| are given. If x is a number, return x.__int__(). For floating point
| numbers, this truncates towards zero.
我对 partial 参数的理解是,加入这么写
functools.partial(func, arg1)
则指定 func 最靠左的那个参数为 arg1
def fun(x, y, z):
print('x: {0}; y: {1}; z: {2}'.format(x, y, z))
f1 = functools.partial(fun, 1)
f1(2, 3)
# Output: 'x: 1; y: 2; z: 3'
我们也可以通过在 parital 中通过指定默认参数来绑定 func 中的参数值
f2 = functools.partial(fun, z=3)
f2(2, 1)
# Output: 'x: 2; y: 1; z: 3'
我的问题
sum_100 = functools.partial(sum, start=100)
print(sum_100([1, 2, 3]))
#TypeError: sum() takes no keyword arguments
sum 函数的说明:
sum(iterable, start=0, /)
Return the sum of a 'start' value (default: 0) plus an iterable of numbers
When the iterable is empty, return the start value.
This function is intended specifically for use with numeric values and may
reject non-numeric types.
既然这样对 sum 函数不行,为什么能成功作用于 int 了
import functools
int2 = functools.partial(int, base=2)
print(int2('10001'))
# Output: '17'
int 函数的解释如下:
class int(object)
| int(x=0) -> integer
| int(x, base=10) -> integer
|
| Convert a number or string to an integer, or return 0 if no arguments
| are given. If x is a number, return x.__int__(). For floating point
| numbers, this truncates towards zero.