关于迭代器问题 困扰我一周了 要疯掉了 求大神
困扰我几天了, 我一直不理解, 我明明把生成器生成迭代器了啊, 为啥说不是迭代对象呢?a = [{'a': 1}, {'b': 2}, {'c': 3}, {'d': 4}, {'e': 5}, {'f': 6}, {'g': 7}, {'h': 8}, {'i': 9}, {'j': 10}, {'k': 11},
{'l': 12}, {'m': 13}, ]
class AA():
def __init__(self):
self.diedaiqi=self.shengchengqi() #
def shengchengqi(self):
self.i = iter(a)
def diaoyong(self):
while True:
print(next(self.diedaiqi))
if __name__ == '__main__':
aa = AA()
aa.diaoyong()
报错TypeError: 'NoneType' object is not an iterator 本帖最后由 jackz007 于 2021-11-4 11:54 编辑
修改这个函数
def diaoyong(self):
while True:
try:
print(next(self.i))
except:
break 迭代器:用iter和next实现叫迭代器
a = [{'a': 1}, {'b': 2}, {'c': 3}, {'d': 4}, {'e': 5}, {'f': 6}, {'g': 7}, {'h': 8}, {'i': 9}, {'j': 10}, {'k': 11},
{'l': 12}, {'m': 13}, ]
class AA:
def __init__(self):
self.iter = iter(a)
def test(self):
while True:
print(next(self.iter))
if __name__ == '__main__':
aa = AA()
aa.test()
生成器:用yield实现就生成器
a = [{'a': 1}, {'b': 2}, {'c': 3}, {'d': 4}, {'e': 5}, {'f': 6}, {'g': 7}, {'h': 8}, {'i': 9}, {'j': 10}, {'k': 11},
{'l': 12}, {'m': 13}, ]
class AA:
def gener(self, s):
while True:
if not len(s):
break
yield s
s = s
def test(self):
Mygener = self.gener(a)
for i in Mygener:
print(i)
if __name__ == '__main__':
aa = AA()
aa.test()
self.diedaiqi=self.shengchengqi()
和
self.diedaiqi=None
没区别 self.diedaiqi=self.shengchengqi()
这个self.shengchengqi()返回的是什么玩意,返回的一个None,你居然和我说,None是一个迭代对象?
页:
[1]