###柯里化 f(x,y) -> g(x)(y)
python 柯里化 f(x,y) -> g(x)(y)
def bigger(x): def inner_bigger(y): return y>x return inner_bigger list(filter(bigger(5),range(10))) #filter返回一个迭代器,用list接收 [6, 7, 8, 9] list(filter(bigger(3),range(10))) [4, 5, 6, 7, 8, 9]
实例化一下:
bigger_3 = bigger(3)
bigger_3(4)
True
bigger_3(2)
False
使用partial 也可以实现柯里化: 用于固定某些参数
def inc(f,x): return f+x def bigger(x,y): return x >y 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. | partial(bigger,y=3) functools.partial(<function bigger at 0x7f264455ad08>, y=3) bigger_3 = partial(bigger,y=3) callable(bigger_3) #判断一个函数是否可以被调用 用callable True
bigger_3(2) #x=2 > y=3 返回false
False
bigger_3(4) #x=4 > y=3 返回True
True
def mang_args(x,y,z,a,b,c):
... print ("x is {}".format(x))
... print ("y is {}".format(y))
... print ("z is {}".format(z))
... print ("a is {}".format(a))
... print ("b is {}".format(b))
... print ("c is {}".format(c))
fn1 = partial(mang_args,a=1,b=2,c=3)
fn1(4,5,6)
x is 4
y is 5
z is 6
a is 1
b is 2
c is 3