「Python」イテレータと StopIteration 例外のサンプル

2021年7月16日

書式
raise StopIteration
使用例

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
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

Python

Posted by arkgame