天天看点

装饰器、迭代器、生成器

装饰器

'''

增加装饰时间模块

1、不修改原有函数内容

2、不修改函数调用方式

import time

def timer(func):

    def deco():

        start_time=time.time()

        func()

        stop_time=time.time()

        print 'running time:',stop_time-start_time

    return deco()

@timer

def test1():

    time.sleep(3)

    print 'int the test1'

增加认证模块

user,passwd='alex','abc123'

def auth(auth_type):

    def outer_wrapper(func):

        def wrapper(*args,**kwargs):

            if auth_type=='local':

                username=raw_input('username:')

                password=raw_input('password:')

                if user==username and password==passwd:

                    print '\033[32;1mUser has passed authentication\033[0m'

                    res=func(*args,**kwargs)

                    return res

                else:

                    exit('\033[31;1mInvalid username or password\033[0m')

            elif auth_type=='ldap':

                print 'no ldap'

        return wrapper

    return outer_wrapper

@auth(auth_type='local')

def index():

    print 'in the index'

    return 'from index'

@auth(auth_type='ldap')

def home():

    print 'in the home'

    return 'from home'

index()

home()

迭代器

迭代器就是有一个next()方法的对象。

迭代器也有一些限制,例如不能向后移动,不能回到开始,也不能复制一个迭代器。如果要再次或同时迭代同个对象,只能去创建另一个迭代器对象。

reversed()内建函数将返回一个反序列访问的迭代器。

enumerate()内建函数同样也返回迭代器。

此外,python还提供一整个itertools模块,它包含各种有用的迭代器。

如:

myTuple=(123,'xyz',45.67)

i=iter(myTuple)

i.next()

如果是一个实际应用程序,那么我们需要把代码放在一个try-except块中。序列现在会自动地产生它们自己的迭代器,所以一个for循环:

for i in seq:

 do_something_to(i)

实际上是这样工作的:

fetch=iter(seq)

while True:

    try:

        i=fetch.next()

    except StopIteration:

        break

    do_something_to(i)

除了序列之外,字典和文件是另外两个可迭代的python数据类型。

生成器

协同程序是可以运行的独立函数调用,可以暂停或者挂起,并从程序离开的地方继续或者重新开始。

挂起返回出中间值并多次继续的协同程序被称为生成器,那就是python的生成器真正做的事。

什么是python式的生成器?从语法上讲,生成器是一个带yield语句的函数。一个函数或者子程序只返回一次,但一个生成器能暂停执行并返回一个中间的结果——那就是yield语句的功能,返回一个值给调用者并暂停执行。当生成器的next()方法被调用的时候,它会准确地从离开地方继续。

python的for循环有next()调用和对StopIteration的处理。

如果想终结一个生成器,可以调用close()方法。

本文转自Grodd51CTO博客,原文链接:http://blog.51cto.com/juispan/1960330,如需转载请自行联系原作者