「Python」イテレータと StopIteration 例外のサンプル
書式
raise StopIteration
使用例
class Test:
# __iter__の実装
def __iter__(self):
self.a = 3
return self
# __next__の実装
def __next__(self):
if self.a <= 15:
x = self.a
self.a *= 2
return x
else:
raise StopIteration #StopIteration 例外
#オブジェクトを生成
cft = Test()
res = iter(cft)
#for文
print("result as follows:")
for x in res:
print(x)
class Test:
# __iter__の実装
def __iter__(self):
self.a = 3
return self
# __next__の実装
def __next__(self):
if self.a <= 15:
x = self.a
self.a *= 2
return x
else:
raise StopIteration #StopIteration 例外
#オブジェクトを生成
cft = Test()
res = iter(cft)
#for文
print("result as follows:")
for x in res:
print(x)
class Test: # __iter__の実装 def __iter__(self): self.a = 3 return self # __next__の実装 def __next__(self): if self.a <= 15: x = self.a self.a *= 2 return x else: raise StopIteration #StopIteration 例外 #オブジェクトを生成 cft = Test() res = iter(cft) #for文 print("result as follows:") for x in res: print(x)
実行結果
result as follows:
3
6
12