那里可以免费建网站,网站建设公司自贡,数字展厅企业展厅,重庆网络推广生成器、迭代器、可迭代对象
生成器 函数体中包含yield关键字的就是生成器 把生成 器传给 next(...) 函数时#xff0c;生成器函数会向前#xff0c;执行函数定义体中的 下一个 yield 语句#xff0c;返回产出的值#xff0c;并在函数定义体的当前位置暂停。等到再次遇到n…生成器、迭代器、可迭代对象
生成器 函数体中包含yield关键字的就是生成器 把生成 器传给 next(...) 函数时生成器函数会向前执行函数定义体中的 下一个 yield 语句返回产出的值并在函数定义体的当前位置暂停。等到再次遇到next才会继续执行。 简单生成器示例
def demo_gen():yield 1yield 2yield 3
gen demo_gen()
print(next(gen))
print(next(gen))
print(next(gen))
print(next(gen)) # 当生成器的值取完了在使用next方法会抛出StopIteration错误生成器表达式 生成器表达式是语法糖:完全可以替换成生成器函数不过有时使用生成器表达式更便利。 代码在ipython(安装pip install ipython)运行的
In [1]: (i for i in range(10))
Out[1]: generator object genexpr at 0x107798200类示例代码
class Sentence:简单的生成器使用yield关键字def __init__(self, text):self.text textself.words RE_WORD.findall(self.text)def __iter__(self):for word in self.words:yield word
迭代器
使用while循环模拟迭代器
s ABC
it iter(s)
while True:try:print(next(it))except StopIteration:del itbreak实现迭代器的必备方法 __next__ 返回下一个可用的元素如果没有元素了抛出StopIteration异常。 __iter__ 返回self以便在应该使用可迭代对象的地方使用迭代器例如for循环中。
实现代码
class IterableDemo:def __init__(self, text):self.text textself.index 0def __iter__(self):return iter(self)def __next__(self):next方法的获取逻辑try:word self.text[self.index]except IndexError:raise StopIterationself.index 1return wordif __name__ __main__:it IterableDemo(Helloworld)print(next(it))print(next(it))print(next(it))
可迭代对象 可迭代对象是指可以通过__iter__和__getitem__方法访问。 其中__getitem__方法没有办法通过issubclass(Sentence, Iterable)判断。 解释器需要迭代对象x时会自动调用iter(x)。 from collections.abc import Iterableclass Sentence:def __iter__(self):return iter(self)print(issubclass(Sentence, Iterable)) # Trueclass Sentence:def __getitem__(self, index):return self.words[index]print(issubclass(Sentence, Iterable)) # False
实现__getitem__方法 如果只实现了__getitem__方法Python会创建一个迭代器尝试按顺序从索引0开始获取元素。 如果尝试失败会返回C object is not iterableC对象不可迭代其中C对象就是所属的类。 def __getitem__(self, index):return self.words[index]实现__iter__方法
def __iter__(self):return iter(self.words)示例代码
class Sentence:def __init__(self, text):self.text textself.words RE_WORD.findall(self.text)def __iter__(self):return iter(self.words)# def __getitem__(self, index):# return self.words[index]def __len__(self):return len(self.words)def __str__(self):return Sentence(%s) % reprlib.repr(self.words)s Sentence(Hello world how are you)
for word in s:print(word)