关于iter()方法
本帖最后由 青出于蓝 于 2022-7-29 07:10 编辑想问关于iter方法的第二种使用,我以下的代码是否get到了精髓,或者说是多此一举呢
class Iter:
def __init__(self):
self.count = 0
def __iter__(self):
return self
def __next__(self):
self.count += 1
if self.count > 3:
raise StopIteration
return self.count
a = Iter()
b = iter(a.__next__, 10)
print(next(b))
本帖最后由 suchocolate 于 2022-7-29 01:03 编辑
__next__里定死了3,外面用10没有意义。不如这样:
class Iter:
def __init__(self, limit=1):
self.count = 0
self.limit = limit
def __iter__(self):
return self
def __next__(self):
self.count += 1
if self.count > self.limit:
raise StopIteration
return self.count
a = Iter(3)
try:
while True:
print(next(a))
except Exception as e:
print(e)
print('=' * 20)
a = Iter(10)
try:
while True:
print(next(a))
except Exception as e:
print(e)
页:
[1]