# 解析Python 偏函数用法全方位实现

Python的functools模块中有一种函数叫“偏函数”，自从接触它以来，发现确实是一个很有用且简单的函数，相信你看完这篇文章，你也有相见恨晚的感觉。

value = int('10000')
print(value)  # 10000

value = int('10000', base=2)
print(value)  # 16

from functools import partial

int2 = partial(int, base=2)
res = int2('10000')
print(res)   # 16

#### 自定义函数的使用

def add(a, b, c):
print('a=',a,'b=',b,'c=',c)
return a + b + c

res = add10(1, 2)   # a= 10 b= 1 c= 2

#### 当入参为可变参数时

def sum(*args):
s = 0
for n in args:
s += n
return s

sum10 = partial(sum, 10)
print(sum10(1))  # 11
print(sum10())   # 10

#### 当入参为可变关键字参数时

D = {'value1':10, 'value2':20}
V = {'Default':100}
def show(**kw):
for k in kw:
print(k, kw.get(k))

showDef = partial(show, **V)
showDef(**D)
# Default 100
# value1 10
# value2 20

#### 当入参为限制的关键字参数时

def student(name, * , age, city):
print('name:',name, 'age:',age, 'city:',city)

studentAge = partial(student, age=20)
studentAge('Tom','Beijing')
# TypeError: student() takes 1 positional argument but 2 positional arguments (and 1 keyword-only argument) were given

studentAge = partial(student, age=20, city='Beijing')
studentAge('Tom') # name: Tom age: 20 city: Beijing