zoukankan      html  css  js  c++  java
  • python学习笔记4:高阶函数,装饰器,生成器,迭代器

    一.高级函数
    1.把一个函数名当作实参传给另一个函数
    2.返回值包含函数名
    >>> def bar():
    ... print ("in the bar")
    ...
    >>> def foo(func):
    ... res=func()
    ... return res
    ...
    >>> foo(bar)
    in the bar

    二.嵌套函数
    在函数中定义另一个函数

    三.装饰器
    装饰器本质上是函数,作用是装饰其他函数,就是为其他函数添加附加功能。
    原则1:不能修改被装饰函数的源代码
    原则2:不能修改被装饰函数的调用方式
    函数及变量:
    >>> def bar():
    ... print("in the bar !")
    >>> bar()
    in the bar !
    >>> f=bar
    >>> f
    <function bar at 0x7f0b3bddba60>
    >>> bar
    <function bar at 0x7f0b3bddba60>
    >>> f()
    in the bar !


    高阶函数+嵌套函数-》装饰器

    import time
    def timer(func):
    def deco(*args,**kwargs):
    start_time=time.time()
    func(*args,**kwargs)
    stop_time=time.time()
    print("the func run time is {time}".format(time=stop_time-start_time))
    return deco
    @timer #test1=timer(test1)
    def test1():
    time.sleep(2)
    print('in the test1')
    @timer
    def test2():
    time.sleep(2)
    print('in the test2')
    test1()
    test2()


    in the test1
    the func run time is 2.000096321105957
    in the test2
    the func run time is 2.0006771087646484

    四.生成器
    1.生成器只有在调用的时候才会生成相应的数据
    2.只记录当前的位置,只有一个__next__方法

    3.生成generator:
    (1)把列表生成器的[],变为()
    >>> L=[x*x for x in range(4)]
    >>> L
    [0, 1, 4, 9]
    >>> g=(x*x for x in range(4))
    >>> g
    <generator object <genexpr> at 0x7f0b3bde6e60>
    >>>
    (2)如果一个函数定义中包含yield关键字,那么这个函数就不再是一个普通函数,而是一个generator
    def fib(max):
    n,a,b=0,0,1
    while n< max:
    yield b
    a,b=b,a+b
    n+=1
    return "done"
    f=fib(6)
    print(f)

    D:ProgramsPythonPython35-32python.exe E:/python/pylearn/oldboy/dayn/day4/genetor2.py
    <generator object fib at 0x01BA17E0>

    4.还可通过yield实现在单线程的情况下实现并发运算的效果
    import time
    def consumer(name):
    print("%s 准备吃包子啦!" %name)
    while True:
    baozi=yield
    print("包子[%s]来了,被[%s]吃了"%(baozi,name))
    def producer(name):
    c=consumer("A")
    c2=consumer("B")
    c.__next__()
    c2.__next__()
    print("老子开始准备做包子啦!")
    for i in range(10):
    time.sleep(1)
    print("做了1个包子,分两半!")
    c.send(i)
    c2.send(i)
    producer("alex")

    运行结果:
    A 准备吃包子啦!
    B 准备吃包子啦!
    老子开始准备做包子啦!
    做了1个包子,分两半!
    包子[0]来了,被[A]吃了
    包子[0]来了,被[B]吃了
    做了1个包子,分两半!
    包子[1]来了,被[A]吃了
    包子[1]来了,被[B]吃了

    四.迭代器
    可以直接作用于for循环的数据类型有以下几种:

    一类是集合数据类型,如list、tuple、dict、set、str等;

    一类是generator,包括生成器和带yield的generator function。

    这些可以直接作用于for循环的对象统称为可迭代对象:Iterable。

    可以使用isinstance()判断一个对象是否是Iterable对象
    而生成器不但可以作用于for循环,还可以被next()函数不断调用并返回下一个值,直到最后抛出StopIteration错误表示无法继续返回下一个值了。

    *可以被next()函数调用并不断返回下一个值的对象称为迭代器:Iterator
    凡是可作用于for循环的对象都是Iterable类型;

    凡是可作用于next()函数的对象都是Iterator类型,它们表示一个惰性计算的序列;

    集合数据类型如list、dict、str等是Iterable但不是Iterator,不过可以通过iter()函数获得一个Iterator对象。

    Python的for循环本质上就是通过不断调用next()函数实现的

  • 相关阅读:
    在浏览器中输入URL并回车后都发生了什么?
    HashMap数据结构
    记录一次mysql死锁
    常见排序(归并排序)
    记录一次redis事故
    jsp与javaBean
    org.hibernate.ObjectNotFoundException: No row with the given identifier exists: [com.zhuoshi.entity.Dep#1]
    Oracle创建表空间报错:O/S-Error: (OS 3) 系统找不到指定的路径
    在myeclipse中maven项目关于ssh整合时通过pom.xml导入依赖是pom.xml头部会报错
    2018idea如何布置tomcat修改URL后连接不到
  • 原文地址:https://www.cnblogs.com/raxxar/p/5786168.html
Copyright © 2011-2022 走看看