Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
学ぶ The Iterator Protocol | Understanding Iterators
Efficient Data Handling in Python

bookThe Iterator Protocol

メニューを表示するにはスワイプしてください

Understanding how Python handles iteration is essential for working with sequences, loops, and many built-in features. At the core of this functionality is the iterator protocol. The iterator protocol is a set of methods that allows objects to be iterated over, meaning you can use them in a for loop or with functions like list() and sum(). In Python, an object is considered iterable if it implements the __iter__ method, which should return an iterator. An iterator is an object that implements both the __iter__ and __next__ methods. The __next__ method returns the next item in the sequence, and raises a StopIteration exception when there are no more items.

123456789101112131415161718
class CountUpTo: def __init__(self, max): self.max = max self.current = 1 def __iter__(self): return self def __next__(self): if self.current > self.max: raise StopIteration value = self.current self.current += 1 return value counter = CountUpTo(3) for number in counter: print(number)
copy

In this example, the CountUpTo class is a custom iterator. It keeps track of the current number and stops iteration when it reaches the maximum value. By defining both __iter__ and __next__, this class can be used in a for loop, which will automatically call __iter__ to get the iterator and then repeatedly call __next__ to retrieve each value.

1. Which of the following best describes the purpose of the __iter__ method in the iterator protocol?

2. Which of the following objects in Python are considered iterable?

question mark

Which of the following best describes the purpose of the __iter__ method in the iterator protocol?

正しい答えを選んでください

question mark

Which of the following objects in Python are considered iterable?

すべての正しい答えを選択

すべて明確でしたか?

どのように改善できますか?

フィードバックありがとうございます!

セクション 1.  1

AIに質問する

expand

AIに質問する

ChatGPT

何でも質問するか、提案された質問の1つを試してチャットを始めてください

セクション 1.  1
some-alt