day4、装饰器件、迭代器和生成器

1、装饰器(函数)

功能:装饰其他函数、为其他函数添加附加功能。

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

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

ps:函数即变量,高阶函数+嵌套函数

1.1函数即变量

def logger():
    pass    
def test1():
    pass
def test2():
    pass

 

def logger():
    pass    
def test1():
    pass
def test2():
    pass

1.2、高阶函数:1、把一个函数名当实参传给另一个函数(不修改函数源代码,增加功能)

def logger():
    pass    

def test(func):
    func()
    print(func)

test(logger)

 或2、返回值中包含函数名(不修改函数的调用方式)

def logger():
    pass    

def test(func):
    func()
   return func

test(logger)

 1.3、嵌套函数( 函数体内声明函数)

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

 1.4、修饰器

不完全版:

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




def test1():
    time.sleep(1)
    print('in the test1')
    stop_time = time.time()
test1=timmer(test1)

test1()
View Code

 

无参数版

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



@timmer #test1=timmer(test1)
def test1():
    time.sleep(1)
    print('in the test1')
    stop_time = time.time()


test1()
View Code

 

 有参数可用版

 1 import time
 2 
 3 def timmer(func):
 4     def warpper(*args,**kwargs):
 5         start_time=time.time()
 6         func()
 7         stop_time=time.time()
 8         print('the func run time is %s'%(stop_time-start_time))
 9     return warpper
10 
11 @timmer #test1=timmer(test1)
12 def test1():
13     time.sleep(3)
14     print('in the test1')
View Code

 

 终极版

 1 user,password='xiaochun','123'
 2 def auth(auth_type):
 3     print('auth_type',auth_type)
 4     def outwrapper(func):
 5         def wrapper(*args,**kwargs):
 6             if auth_type=='local':
 7                 username=input("username:")
 8                 passwd=input("password:")
 9                 if user==username and passwd==password:
10                     print('\033[32;1mUser has logied\033[0m')
11                     return func(*args,**kwargs)
12                 else:
13                     print('\033[41;1mInvalid user\033[0m')
14             else :
15                 print('用ldcp登陆')
16         return wrapper
17     return outwrapper
18 def index():
19     print('welcome to index page')
20 
21 @auth(auth_type='ldap')#home=aut
22 def bbs():
23     print('welcome to bbs')
24 
25 @auth(auth_type='local')
26 def home():
27     print('welcome to home')
28     return 'from home'
29 
30 index()
31 home()
32 bbs()
View Code

 2、迭代器和生成器

2.1  列表生成式

使代码更简洁

[i*2 for i in rang(10)]
[func(i) for i in range(10)]

 2.1生成器

(推算列表后面的元素(通项公式、递推公式))只有调用时才会生成相应的数据

只记录当前位置,只有一个方法__next__()

1、列表生成式

a=(i*3 for i in range(10))

 不支持

a[5]

只能循环一个一个取 

循环

a.__next__()

 2、制作一个生成器:yield (返回当前状态的值,)单线程 做并行处理(中断)

def fib(max):
    n,a,b = 0,0,1
    while n<max:
        yield b
        a,b = b,a+b
        n = n+1
    return 'done'

print(fib(10))
View Code

 并行操作 

send调用yield并传值

def consumer(name):
    print('%s准备吃包子'%(name))
    while True:
        baozi = yield
        print('包子[%s]coming,被[%s]吃了'%(baozi,name))
    return 'done'
c=consumer('nihao')


def producer(name):
    c=consumer('A')
    c2=consumer('B')
    c2.__next__()
    c.__next__()
    for i in range(10):
        b = '猪肉大葱'
        print('[%s] make two baozi [%s]'%(name,b))

        c.send(b)
        c2.send(b)

producer('dashi')
View Code

2.2 迭代器

isinstance((x for x in range(10) ),Iterator)

 

可迭代的

1、集合数据类型

2、generator 、包括生成器和带yield 的generation

可以用于for循环的对象叫可迭代对象

from collections import Iterable
isinstance([1,2,34],Iterable)

 

迭代器:可以被next()调用并不断返回下一个值的对象称为迭代器:Iterator

from collections import Iterator
isinstance(iter((x for x in range(10) )),Iterator)

 可迭代对象但不是迭代器变成迭代器

Iterator甚至可以表示一个无限大的数据流

 

结论:

1、可以用于for循环的对象叫可迭代对象

2、可以被next()调用并不断返回下一个值的对象称为迭代器

3、集合类型如list、dict、str等Iterator可以用iter()函数获得一个Iterator对象

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

 

posted on 2018-07-22 16:47  LittleSpring  阅读(136)  评论(0编辑  收藏  举报