python编程--迭代器,生成器和装饰器

简述迭代器,生成器和装饰器

迭代器

迭代是Python访问集合元素的一种方式。

迭代器是一个可以记住遍历的位置的对象。
迭代器对象从集合的第一个元素开始访问,直到所有的元素被访问完结束。迭代器只能往前不会后退。

迭代器有两个基本的方法:iter() 和 next()。

newList = [1, 2]
it = iter(newList) # 创建迭代器对象
print (it)
print (next(it))
print (it.__next__())
---------------------------------------------------
<list_iterator object at 0x03A51FB8>
1
2

用for进行遍历

list=[1,2,3]
it = iter(list)    # 创建迭代器对象
for x in it:
    print (x, end=" ")
---------------------------------------------------
1 2 3    

也可以使用 next() 函数:

import sys  

list = [1, 2, 3]
it = iter(list)  # 创建迭代器对象

while True:
    try:
        print(next(it))
    except StopIteration:
        sys.exit()
---------------------------------------------------
1
2
3

生成器

生成器是一个返回迭代器的函数,只能用于迭代操作,更简单点理解生成器就是一个迭代器。

在调用生成器运行的过程中,每次遇到 yield 时函数会暂停并保存当前所有的运行信息,返回 yield 的值, 并在下一次执行 next() 方法时从当前位置继续运行。

调用一个生成器函数,返回的是一个迭代器对象。

当next()方法第一次被调用的时候,生成器函数才开始执行,执行到yield语句处停止
next()方法的返回值就是yield语句处的参数(yielded value)

每调用一次生成器的next()方法,就会执行生成器中的代码,知道遇到一个yield或者return语句。yield语句意味着应该生成一个值。return意味着生成器要停止执行,不在产生任何东西。

生成器的编写方法和函数定义类似,只是在return的地方改为yield。生成器中可以有多个yield。当生成器遇到一个yield时,会暂停运行生成器,返回yield后面的值。当再次调用生成器的时候,会从刚才暂停的地方继续运行,直到下一个yield。生成器自身又构成一个循环器,每次循环使用一个yield返回的值。

import sys
 
def fibonacci(n): # 生成器函数 - 斐波那契
    a, b, counter = 0, 1, 0
    while True:
        if (counter > n): 
            return
        yield a
        a, b = b, a + b
        counter += 1
        
f = fibonacci(10)
while True:
    try:
        print (next(f), end=" ")
    except StopIteration:
        sys.exit()
---------------------------------------------------
0 1 1 2 3 5 8 13 21 34 55 

详细说明:
在这个例子中,f = fibonacci(10)
f 是一个迭代器,由生成器返回生成
进入while 循环后:
运行print (next(f), end=" “)
调用fibonacci函数,yield a后,print a的值;
由于while循环未结束:第二次到 print (next(f), end=” ")时:
从yield a 处继续运行程序
a, b = b, a + b
counter += 1
此时因为函数中的while条件成立,循环继续…

另一个例子:

letter = ['a', 'b']
num = ['1', '2']

#注意一个是()一个是[]
list = (a + b for a in letter for b in num)
print(list)
for a in list:
    print(a)

list = [a + b for a in letter for b in num]
print(list)
---------------------------------------------------
<generator object <genexpr> at 0x011A9568>
a1
a2
b1
b2
['a1', 'a2', 'b1', 'b2']

装饰器

def new_decorator(func):
    def wrapTheFunction():
        print("start")
        func()
        print("end")
    return wrapTheFunction

def requiring_decoration():
    print("In requiring decoration")

onedecoration = new_decorator(requiring_decoration)
onedecoration()
---------------------------------------------------
start
In requiring decoration
end
def new_decorator(func):
    # def wrapTheFunction():
    print("start")
    func()
    print("end")
    # return wrapTheFunction

def requiring_decoration():
    print("In requiring decoration")

decoration = new_decorator(requiring_decoration)
---------------------------------------------------
start
In requiring decoration
end

using @

def new_decorator(func):
    # def wrapTheFunction():
    print("start")
    func()
    print("end")
    # return wrapTheFunction

@new_decorator
def requiring_decoration():
    print("In requiring decoration")

@ can be replaced by using
decoration = new_decorator(requiring_decoration)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值