python-第二块,笔记整理和学习内容复习(day7)

DAY7

学习内容

  今天学习了装饰器和生成器,装饰器代码如下:

import time
def deco(func):      #高阶函数1,实现装饰功能,但是修改了原函数的调用方式
    start_time = time.time()
    func()
    stop_time = time.time()
    print("the run time is %s"%(stop_time-start_time))

def test1():
    time.sleep(1)
    print("in the test1")

deco(test1)
test1()

def deco(func):      #高阶函数2,未能实现装饰功能,但是未了原函数的调用方式
    start_time = time.time()
    stop_time = time.time()
    print("the run time is %s"%(stop_time-start_time))
    return func

def test1():
    time.sleep(1)
    print("in the test1")

test1()

def deco(func):
    def func1():      #高阶函数2,未能实现装饰功能,但是未了原函数的调用方式
        start_time = time.time()
        func()
        stop_time = time.time()
        print("the run time is %s"%(stop_time - start_time))       #声明一个函数“变量”
    return func1                                                    #返回这个函数“变量”内存地址

@deco            #test1 = deco(test1)                                #添加装饰器
def test1():
    time.sleep(1)
    print("in the test1")

test1()

  其中装饰器需要高阶函数和嵌套函数。

然后学习了生成器的知识,代码如下:

def fei(max):              #斐波那契额函数
    a,b,n = 0,1,0
    while n < max:
        print(b)
        a,b = b,a+b
        n += 1

def feib(max):
    a,b,n = 0,1,0
    while n < max:
        yield b            #将print 改为 yield 变成斐波那契生成器
        a,b = b,a+b
        n += 1
f = feib(10)
print(f.__next__())
# for i in fei(10):
#     print(i)

笔记

装饰器

  1、定义:本质是函数,(装饰其他函数)就是为其他函数添加附加功能。

  2、原则:a 不能修改被装饰的函数的源代码

        b 不能修改被装饰的函数的调用方式

  3、实现装饰器知识储备

       a 函数即“变量”

       b 高阶函数,             1)把一个函数名当做实参传给另一个函数,可以在不修改原函数的源代码情况下添加功能,但修改了调用方式

                   2)返回值中包含函数名,不修改函数的调用方式,但是不能实现装饰器功能

       c 嵌套函数

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

  4、若原函数中游形参,则需要在装饰器函数中加上*args、**kwargs

生成器

  1、只会在调用的时候产生相应的数据

  2、只记录当前位置,只有一个_next_()方法