📜  Python __iter __()和__next __()| 将对象转换为迭代器(1)

📅  最后修改于: 2023-12-03 14:45:55.837000             🧑  作者: Mango

Python __iter__() and __next__() | Converting objects to iterators

In Python, objects can be converted into iterators by defining the __iter__() and __next__() methods. These two methods provide the functionality required to make an object iterable.

The __iter__() Method

The __iter__() method is used to return an iterator object. It is called once when the iteration is initialized on an object. Here's an example:

class MyIterator:
    def __init__(self, items):
        self.items = items
        self.index = 0
    
    def __iter__(self):
        return self
    
    def __next__(self):
        if self.index < len(self.items):
            item = self.items[self.index]
            self.index += 1
            return item
        else:
            raise StopIteration

In this example, the MyIterator class is defined, which has an __iter__() method that returns the iterator object, which is the object itself. The __next__() method retrieves the next item from the list of items, and raises a StopIteration exception when the iteration is complete.

Using the Iterator

To use the iterator, we create an instance of the MyIterator class, and then iterate over it using a for loop or the next() function. Here's an example:

items = [1, 2, 3]
my_iterator = MyIterator(items)

for item in my_iterator:
    print(item)

# Output: 1
#         2
#         3

In this example, an instance of the MyIterator class is created with a list of numbers. The for loop is used to iterate over the items in the list, calling the __next__() method on the iterator each time.

The next() Function

The next() function can also be used to retrieve the next item from an iterator. Here's an example:

items = ['apple', 'banana', 'cherry']
my_iterator = MyIterator(items)

print(next(my_iterator))  # Output: 'apple'
print(next(my_iterator))  # Output: 'banana'
print(next(my_iterator))  # Output: 'cherry'

In this example, the next() function is used to retrieve each item from the iterator, starting with the first item and ending with the last.

Conclusion

The __iter__() and __next__() methods provide a way to convert any object into an iterable, allowing it to be used with the for loop and the next() function. By defining these two methods, an object gains the ability to be iterated over just like a list or tuple.