classPowNumber(object):"""
迭代器
生成1,2,3,4,5,... 数的平方
"""
value =0def__next__(self):
self.value +=1if self.value >10:raise StopIteration
return self.value * self.value
def__iter__(self):return self
if __name__ =='__main__':pow= PowNumber()# print(pow.__next__())# print(pow.__next__())# print(pow.__next__())# print(pow.__next__())print(next(pow))print(next(pow))print(next(pow))print(next(pow))#循环迭代器for i inpow:print(i)
# -*- encoding: utf-8 -*-"""
@File : generator.py
@Time : 2020/10/16 10:07
@Author : XUDA
@Email : gudianpai@qq.com
@Software: PyCharm
"""#列表推导式
l =[x * x for x in[1,2,3,4,5]]print(l)
l1 =(x * x for x in[1,2,3,4,5])print(l1)# E:\py-learn\xd_cbir\venv\Scripts\python.exe E:/py-learn/chapter09/generator.py# [1, 4, 9, 16, 25]# <generator object <genexpr> at 0x000002832EE1CA50>print(l1.__next__())print(next(l1))# 1# 4
# -*- encoding: utf-8 -*-"""
@File : generator_test.py
@Time : 2020/10/16 10:13
@Author : XUDA
@Email : gudianpai@qq.com
@Software: PyCharm
"""defpow():yield1yield2yield3yield4defpow_number():return(x * x for x in[1,2,3,4,5])defpow_number():for x in[1,2,3,4,10]:yield x * x
if __name__ =='__main__':
rest =pow()print(rest)# #<generator object pow at 0x00000199185BCA50># print(next(rest))# print(next(rest))# print(next(rest))# for i in rest:# print(i)
rest = pow_number()print(rest)print(next(rest))print(next(rest))print(next(rest))print(next(rest))print(next(rest))