16.高阶函数和柯里化
2020-12-22 本文已影响0人
Stone_説
1.高阶函数
参数或者返回值为函数的含函数,称之为其高阶函数
1.1 例1
>>> def counter(base):
... def inc(step=1):
... nonlocal base
... base += step
... return base
... return inc #表示符是一个局部变量,每次都需要创建一次
>>> c1 = counter(10)
>>> c2 = counter(10)
>>> c1() == c2()
True
>>> c1() == c2()
True
>>> c1(),c2()
(13, 13)
>>> counter(10) == counter(10)
False
>>> counter(10) #counter(10)返回的是一个内部函数,不过并不是同一个函数
<function counter.<locals>.inc at 0x7f10607ce9d0>
>>> counter(10)
<function counter.<locals>.inc at 0x7f10607ce940>
>>> c1 == c2
False
>>> c1 is c2
False
>>> id(counter(10)),id(counter(10)) #仅仅是地址复用,使用完地址被释放
(139708315003200, 139708315003200)
>>> c1,id(c1) #用变量记录两个不同的函数对象时候,则不会释放,故地址不一样
(<function counter.<locals>.inc at 0x7f10607ce820>, 139708315002912)
>>> c2,id(c2)
(<function counter.<locals>.inc at 0x7f10607ce8b0>, 139708315003056)
1.2 例2
>>> def inc(step=1): #外部的全局变量,地址没用变化过,始终如一
... return 1
>>> def counter(base): #此处返回的是一个函数
... return inc
>>> print(inc,id(inc))
<function inc at 0x7f238e369790> 139790686525328
>>> c1 = counter(10)
>>> c1
<function inc at 0x7f238e369790>
>>> c2 = counter(10)
>>> c2
<function inc at 0x7f238e369790>
>>> c1 == c2 ,c1 is c2
(True, True)
2.柯里化
将原来接受两个参数变成新的接受一个参数的函数的过程。新的函数返回一个以原有第二个参数为参数的函数
z=f(x,y) --> z=f(x)(y)的形式
>>> def add(x,y):
... return x+y
...
>>> add(4,5)
9
>>> def add1(x):
... def foo(y):
... return x+y
... return foo
>>> fn = add1(100)
>>> fn(100)
200
练习1:add(x,y,z) --> add(x)(y,z)
>>> def add(x):
... def foo(y,z):
... return x+y+z
... return foo
>>> a = add(5)
>>> a(4,5)
14
练习2:add(x,y,z) --> add(x)(y)(z)
>>> def add(x):
... def foo1(y):
... def foo2(z):
... return x+y+z
... return foo2
... return foo1
>>> s = add(3)
>>> s(4)(10)
17
练习3:add(x,y,z) --> add(x,y)(z)
>>> def add(x,y):
... def foo(z):
... return x+y+z
... return foo
>>> s = add(2,5)
>>> s(10)
17