day4装饰器-迭代器&&生成器

一、装饰器

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

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

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

实现装饰器知识储备:

1、函数及“变量”

2、高阶函数

     a、把一个函数名当做实参传给另一个函数(在不修改被装饰器函数源代码的情况下为其添加新功能)

     b、返回值中包含函数名

3、嵌套函数

高阶函数+嵌套函数 = 装饰器

   延迟3秒

import time

def test1():
     time.sleep(3)
     print('in the test1')
test1()#延迟3秒

例一:装饰器

def bar ():
    print("in the bar")
def foo ():
    print ("in the foo")
    bar()
foo()

例二:

def deco(func):
    start_time = time.time()
    func()
    return func
    stop_time = time.time()
    print ("in func run time is %s" %(stop_time-start_time))
return deco
def foo ():
    print("in the foo")
    bar()
def bar():
    print("in the bar")
foo()

例三:

import time
def timer(func):
    def deco (*args, **kwargs):
        start_time = time.time()
        func(*args, **kwargs)
        stop_time = time.time()
        print("in func run time is %s" %(stop_time- start_time))
    return deco
@timer  #等于test1 = timer(test1)
def test1():
    time.sleep(3)
    print('in the test1')
test1()
@timer
def test2(name,age):
    time.sleep(3)
    print("in the :",name age)
test2('liudong',23)

例四:终极装饰器

user,passwd = 'liudong','123'
def auth (auth_type):
    print("auth_func:",auth_type)
    def outer_wrapper(func):
        def wrapper(*args, **kwargs):
            print("wrapper func args:", *args, **kwargs)
            if auth_type == "local":
                username = input("Username:").strip()
                password = input("Password:").strip()
                if user == username and passwd == password:
                    print("33[32;1mUser has passed authentication33[0m")
                    res = func(*args, **kwargs)#form home
                    print("------------after authentication ")
                    return res
                else:
                    exit("33[31;1mInvalid username or password33[0m")
            elif auth_type == "ldap":
                print("不会-------------")
        return wrapper
    return outer_wrapper
def index():
    print("welcome to index page")
@auth(auth_type="local") #home = wrapper
def home ():
    print("welcome to home page")
    return "form home"
@auth(auth_type="ldap")
def bbs():
    print("welcome to bbs page")
index()
print(home()) #wrapper()
bbs()

匿名函数:

res = filter(lambda n:n>5,range(10))
for i in res:
    print(i)

#print(globals())  打印整个文件里的所有你变量

二、迭代器&生成器

1、只有在调试时,才会生成相应的数据

2、c.__nest__ 一个一个的往下生成,只记录当前的位置,之前生成过的就没了。

3、只有一个__nest__()方法

生成器

def fib (max):
    n, a, b = 0, 0, 1
    while n < max:
        yield b
        a, b = b, a + b
        n = n + 1
    return '------------done-------------'
g = fib(10)
while True:
    try:
        x = next(g)
        print('g:', x)
    except StopAsyncIteration as e:
        print('Generator return value:', e.value)
        break

生成器并行

def consumer(name):
    print("%s准备吃包子了" %name)
    while True:
        baozi = yield
        print("包子[%s]来了,被[%s]吃了" %(baozi,name))
c = consumer("liudong")
c.__next__()
c.send('胡萝卜馅,人肉馅')

def producer(name):
    c = consumer('A')
    c2 = consumer('B')
    c.__next__()
    c2.__next__()
    print("老子开始吃包子啦!")
    for i in range(5):
        time.sleep(1)
        print("做了1个包子,分两半!")
        c.send(i)
        c2.send(i)
producer("liudong")

#迭代器 可以使用isinstance()判断一个对象是否是Iterator(迭代器)对象

json序列化

info = {'name':'liudong','age':23}
f = open("test.txt","w")
f.write(json.dumps(info))
f.close()
原文地址:https://www.cnblogs.com/liuyansheng/p/5769552.html