一 函数对象

函数同样可以作为对象复制给一个变量,如下:

f = abs;
print(f(-10))
f = 'abs';
print(f) def add(a,b,f):
return f(a) + f(b) print(add(-1,2,f))

map 函数, map函数接受一个函数变量,第二个参数为一个可迭代对象,最后返回一个迭代器,由于迭代器的惰性,需要用list()函数返回所有元素。

def squart(n):
return n* n; print(map(squart,range(1,11) ) )
print(list(map(squart,range(1,11) ) ))

reduce函数, reduce函数接受两个参数,第一个参数同样是函数对象f,f必须接受两个参数,并且返回和参数同类型的数据。第二个参数为一个可迭代序列。

def func(a, b):
return a + b print(reduce(func, range(1,11)))

reduce和map函数不一样,reduce返回的是一个最终值

reduce(f,[x1, x2, x3, x4]) = f(f(f(x1,x2),x3),x4)

可以通过reduce和map函数搭配,将一个字符串转化为整数

def str2int(str):
def char2int(c):
return {'':0,'':1,'':2,'':3,'':4,'':5,'':6,'':7,'':8,'':9}
def convertnum(a,b):
return a*10 + b
return reduce(convertnum, map(char2int, str)) print(str2int(""))

filter 函数,filter函数同样有两个参数,第一个参数为函数对象,返回值为bool类型,第二个参数为可迭代序列,返回值为迭代器,

同样需要list()转化为序列。下面用filter和生成器实现一个素数生成器函数

def odd_generater():
n = 1
while True:
n = n+1
yield n def primer_generater():
yield 2
it = odd_generater()
while(True):
n = next(it)
yield n
it = filter(lambda x:x%n > 0, it)

打印测试:

for i in primer_generater():
if(i < 100):
print (i)
else:
break

sorted 函数,第一个接受一个list,第二个为比较的规则,可以不写

print(sorted(["Abert","cn","broom","Dog"]) )

print(sorted(["Abert","cn","broom","Dog"], key = str.lower))

print(sorted(["Abert","cn","broom","Dog"], key = str.lower, reverse = True))

二  函数封装和返回

def lazy_sum(*arg):
def sum():
x = 0
for i in arg:
x = x +i
return x
return sum f = lazy_sum(2,3,1,6,8)
print(f())

定义了一个lazy_sum函数,函数返回内部定义的sum函数。可以在函数A内部定义函数B,调用A返回函数B,从而达到函数B延时调用。

闭包:

在函数A内部定义函数B,函数B内使用了函数A定义的局部变量或参数,这种情况就是闭包。

使用闭包需要注意,在函数B中修改了函数A 定义的局部变量,那么需要使用nonlocal关键字。如果在函数B中修改了全局变量,那么需要使用global关键字。

def lazy_sum(*arg):
sums = 0
def sum():
for i in arg:
nonlocal sums
sums = sums + i
return sums
return sum f1 = lazy_sum(1,3,5,7,9)
f2 = lazy_sum(1,3,5,7,9)
print(f1 == f2)
print(f1() )
print(f2() )

匿名函数:lambda, lambda后面跟函数的参数,然后用:隔开,写运算规则作为返回值

it = map(lambda x:x*x, (1,3,5,7,9))
print(list(it)) def lazy_squart():
return lambda x:x*x
f = lazy_squart()
print(f(3) )

装饰器: 装饰器实际就是函数A中定义了函数B,并且返回函数B,为了实现特殊功能,如写日志,计算时间等等。

先看个返回函数,并且调用的例子

def decoratorfunc(func):
def wrapperfunc():
print('func name is: %s'%(func.__name__))
func()
return wrapperfunc def helloworld():
print('Helloworld !!!') helloworld = decoratorfunc(helloworld)
helloworld()

以后每次调用helloword,不仅会打印Helloworld,还会打印函数名字。

python提供装饰器的功能,可以简化上面代码,并且实现每次调用helloworld函数都会打印函数名字。

def decoratorfunc(func):
def wrapperfunc(*args, **kw):
time1 = time.time()
func(*args, **kw)
time2 = time.time()
print('cost %d secondes'%(time2-time1))
return wrapperfunc @decoratorfunc
def output(str):
print(str)
time.sleep(2) output('hello world!!!')

如果函数带参数,实现装饰器可以内部定义万能参数的函数

def decoratorfunc(func):
def wrapperfunc(*args, **kw):
time1 = time.time()
func(*args, **kw)
time2 = time.time()
print('cost %d secondes'%(time2-time1))
return wrapperfunc @decoratorfunc
def output(str):
print(str)
time.sleep(2) output('hello world!!!')

装饰器执行@decoratorfunc相当于

output = decoratorfunc(output)
output('hello world!!!')

如果装饰器需要传入参数,那么可以增加多一层的函数定义,完成装饰器参数传入和调用。

def decoratorfunc(param):
def decoratorfunc(func):
def wrapperfunc(*arg, **kw):
print('%s %s' %(param, func.__name__))
func(*arg, **kw)
return wrapperfunc
return decoratorfunc @decoratorfunc('execute')
def output(str):
print(str) output('nice to meet u')
print(output.__name__)

#实际执行过程
decorator = decoratorfunc('execute')
output = decorator(now)

output('nice to meet u')

执行print(output.__name__)发现打印出的函数名字不是output而是wrapperfunc,这对以后的代码会有影响。

可以通过python提供的装饰器@functools.wraps(func) 完成函数名称的绑定

def decoratorfunc(param):
def decoratorfunc(func):
@functools.wraps(func)
def wrapperfunc(*arg, **kw):
print('%s %s' %(param, func.__name__))
func(*arg, **kw)
return wrapperfunc
return decoratorfunc @decoratorfunc('execute')
def output(str):
print(str) print(output.__name__)

print(output.__name__)显示为output,这符合我们需要的逻辑。

三  偏函数

如函数 int(a, base = 2) 可以实现一个字符串根据base提供的进制,转化成对应进制的数字。

可以通过偏函数,实现指定参数的固定,并且生成新的函数

intnew = functools.partial(int, base = 2)
print(intnew(''))

也可以自己定义函数:

def add(a,b):
return a+b
print(add(3,7)) addnew = functools.partial(add, 3)
print(addnew(7)) addnew2 = functools.partial(add, b = 7)
print(addnew2(3))

函数部分介绍到此为止,我的公众号,谢谢关注:

 

python学习笔记(六) 函数式编程的更多相关文章

  1. python学习笔记011——函数式编程

    1 函数式编程 面向对象 ,面向过程 ,函数式编程 侧重函数的作用,注重函数结果的传递 函数可以被赋值,也可以接受其他的值 2 函数式编程特点 1.函数是一等公民 与其他变量一样,可以赋值和被赋值,可 ...

  2. Python学习笔记6 函数式编程_20170619

    廖雪峰python3学习笔记: # 高阶函数 将函数作为参数传入,这样的函数就是高阶函数(有点像C++的函数指针) def add(x, y): return x+y def mins(x, y): ...

  3. JS 学习笔记 (六) 函数式编程

    1.函数闭包 1.1 概述 JavaScript采用词法作用域,函数的执行依赖于变量作用域,这个作用域是在函数定义时决定的,而不是函数调用时决定的. 为了实现这种词法作用域,JavaScript函数对 ...

  4. Python学习笔记之函数式编程

    python中的高阶函数 高阶函数就是 变量名指向函数,下面代码中的变量abs其实是一个函数,返回数字的绝对值,如abs(-10) 返回 10 def add(x,y,f): return f(x) ...

  5. python学习笔记1 -- 函数式编程之高阶函数 sorted排序

    python提供了很强大的内置排序函数,妈妈再也不担心我不会写冒泡排序了呀,sorted函数就是这个排序函数,该函数参数准确的说有四个,sorted(参数1,参数2,参数3,参数4). 参数1 是需要 ...

  6. python学习笔记1 -- 函数式编程之高阶函数 map 和reduce

    我用我自己,就是高阶函数,直接表现就是函数可以作为另一个函数的参数,也可以作为返回值 首先一个知识点是 函数的表现形式,印象中的是def  fw(参数)这种方式定义一个函数 python有很多的内置函 ...

  7. python学习笔记1 -- 函数式编程之高阶函数 使用函数作为返回值

    使用函数作为返回值,看起来就很高端有木有,前面了解过函数名本身就是一个变量,就比如abs()函数,abs只是变量名,而abs()才是函数调用,那么我们如果把ads这个变量作为返回值返回会怎么样呢,这就 ...

  8. python学习笔记1 -- 函数式编程之高阶函数 filter

    filter 函数用于过滤序列,与map 和reduce函数类似,作为高阶函数,他们也是同样的使用方法,filter(参数1, 参数2),参数1是一个函数,而参数2是一个序列. filter的作用是根 ...

  9. Python学习笔记六

    Python课堂笔记六 常用模块已经可以在单位实际项目中使用,可以实现运维自动化.无需手工备份文件,数据库,拷贝,压缩. 常用模块 time模块 time.time time.localtime ti ...

随机推荐

  1. mysql5.5 升级到 5.7 的坑

    1.大概思路,docker 新启一个mysql5.7 端口映射到3307 2. 导出5.5 的.sql文件,导入5.7中 3.测试通过后,可将5.5关闭.5.7端口改回3306 GRANT ALL P ...

  2. 王者荣耀交流协会 — Alpha阶段中间产物

    1. 版本控制 Coding :https://git.coding.net/SuperCodingChao/PSPDaily.git 2. 软件功能说明书 软件功能说明书发布在小组成员袁玥同学的博客 ...

  3. 改进意见的答复及bug重现

    各组对本组的互评链接如下 Thunder:http://www.cnblogs.com/vector121/p/7905300.html 王者荣耀交流协会:http://www.cnblogs.com ...

  4. 2018软工实践—Alpha冲刺(7)

    队名 火箭少男100 组长博客 林燊大哥 作业博客 Alpha 冲鸭鸭鸭鸭鸭鸭鸭! 成员冲刺阶段情况 林燊(组长) 过去两天完成了哪些任务 协调各成员之间的工作 学习MSI.CUDA 试运行软件并调试 ...

  5. WPF/MVVM快速指引

    简介 最近微软推出了UWA,又是一波新的C#+xaml学习热.好多小伙伴都对MVVM感觉很好奇,但是有些地方也有点难以理解.特意写了这边文章,希望对你有帮助. 这边文章会很长,所以我会用几个例子的形式 ...

  6. DNS缓存服务器的配置步骤

    yum安装bind 编辑主配置文件/etc/named.conf 修改全局配置文件段        listen-on  port 53 {172.16.19.45;}; //allow-query ...

  7. SSL 重点SSL会话步骤

    SSL.TLS协议 在wiki百科查看下,两者的区别 实现SSL协议的软件 OpenSSL开源软件 SSL会话步骤 1:客户端向服务端索取CA证书,然后验证证书   2:客户端与服务端约定一个通信中使 ...

  8. python实现进制之间的转换

    十进制转36进制: #36位映射模板 loop = '0123456789abcdefghijklmnopqrstuvwxyz' # 测试用例输入 n = a = [] : a.append( loo ...

  9. crontab & php实现多进程思路

    <?php $startTime = time(); while(1) { if (time() - $startTime > 600) { exit; } // ... Do SomeT ...

  10. Java 中 Vector、ArrayList、List 使用深入剖析

    线性表,链表,哈希表是常用的数据结构,在进行Java开发时,JDK已经为我们提供了一系列相应的类来实现基本的数据结构.这些类均在java.util包中.本文试图通过简单的描述,向读者阐述各个类的作用以 ...