python生成器和迭代器

1.迭代器

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

含有__iter__方法的被称为可迭代对象

可以用作for循环的对象称为可迭代对象

  1. 集合数据类型 如  list   tuple   dict  set  str

  2. generator   包括生成器和带yield的enerator  func

2.生成器

带有 yield 关键字的的函数在 Python 中被称之为 generator(生成器)。Python 解释器会将带有 yield 关键字的函数视为一个 generator 来处理。一个函数或者子程序都只能 return 一次,但是一个生成器能暂停执行并返回一个中间的结果 —— 这就是 yield 语句的功能 : 返回一个中间值给调用者并暂停执行。

from collections import Iterable
from collections import Iterator
from collections import Generator

def odd():
    print('step 1')
    yield 1
    print('step 2')
    yield(3)
    print('step 3')
    yield(5)

ge = odd()
print(isinstance(ge, Iterator))
print(isinstance(ge, Iterable))
print(isinstance(ge, Generator))
print(type(ge))
# 结果
# True
# True
# True
# <class 'generator'>

3.装饰器

什么是装饰器(Decorator)

本质上:是一个返回函数的高阶函数。

生产上,什么时候用装饰器?

当我们想要给一个函数func()增加某些功能,但又不希望修改func()函数的源代码的时候就需要用装饰器了。(在代码运行期间动态增加功能)

def  outer(main_func):
	def wrapper(request,*args,**kwargs):
		if request.session.get('username'):
			return main_func(request)
		else:
			return HttpResponse('please login')
	return wrapper

@outer()调用装饰器


python生成器和迭代器
http://www.jcwit.com/article/348/
作者
Carlos
发布于
2018年6月17日
许可协议