瞅瞅我的新 Git 课! 嘿!瞅瞅我的新 Git 课! 嘿!GitByBit.com 上有我的新 Git 课,瞅瞅! 嘿!想来点 Git 的爽复习?GitByBit.com 上我的新课,瞅瞅!
迭代器

Python 迭代器模式讲解和代码示例

迭代器是一种行为设计模式 让你能在不暴露复杂数据结构内部细节的情况下遍历其中所有的元素

在迭代器的帮助下 客户端可以用一个迭代器接口以相似的方式遍历不同集合中的元素

复杂度

流行度

使用示例 该模式在 Python 代码中很常见 许多框架和程序库都使用它来提供遍历其集合的标准方式

识别方法 迭代器可以通过导航方法 例如 next previous 来轻松识别 使用迭代器的客户端代码可能没有其所遍历的集合的直接访问权限

概念示例

本例说明了迭代器设计模式的结构并重点回答了下面的问题

  • 它由哪些类组成
  • 这些类扮演了哪些角色
  • 模式中的各个元素会以何种方式相互关联

main.py: 概念示例

from __future__ import annotations
from collections.abc import Iterable, Iterator
from typing import Any


"""
To create an iterator in Python, there are two abstract classes from the built-
in `collections` module - Iterable,Iterator. We need to implement the
`__iter__()` method in the iterated object (collection), and the `__next__ ()`
method in theiterator.
"""


class AlphabeticalOrderIterator(Iterator):
    """
    Concrete Iterators implement various traversal algorithms. These classes
    store the current traversal position at all times.
    """

    """
    `_position` attribute stores the current traversal position. An iterator may
    have a lot of other fields for storing iteration state, especially when it
    is supposed to work with a particular kind of collection.
    """
    _position: int = None

    """
    This attribute indicates the traversal direction.
    """
    _reverse: bool = False

    def __init__(self, collection: WordsCollection, reverse: bool = False) -> None:
        self._collection = collection
        self._reverse = reverse
        self._sorted_items = None  # Will be set on first __next__ call
        self._position = 0

    def __next__(self) -> Any:
        """
        Optimization: sorting happens only when the first items is actually
        requested.
        """
        if self._sorted_items is None:
            self._sorted_items = sorted(self._collection._collection)
            if self._reverse:
                self._sorted_items = list(reversed(self._sorted_items))

        """
        The __next__() method must return the next item in the sequence. On
        reaching the end, and in subsequent calls, it must raise StopIteration.
        """
        if self._position >= len(self._sorted_items):
            raise StopIteration()
        value = self._sorted_items[self._position]
        self._position += 1
        return value


class WordsCollection(Iterable):
    """
    Concrete Collections provide one or several methods for retrieving fresh
    iterator instances, compatible with the collection class.
    """

    def __init__(self, collection: list[Any] | None = None) -> None:
        self._collection = collection or []


    def __getitem__(self, index: int) -> Any:
        return self._collection[index]

    def __iter__(self) -> AlphabeticalOrderIterator:
        """
        The __iter__() method returns the iterator object itself, by default we
        return the iterator in ascending order.
        """
        return AlphabeticalOrderIterator(self)

    def get_reverse_iterator(self) -> AlphabeticalOrderIterator:
        return AlphabeticalOrderIterator(self, True)

    def add_item(self, item: Any) -> None:
        self._collection.append(item)


if __name__ == "__main__":
    # The client code may or may not know about the Concrete Iterator or
    # Collection classes, depending on the level of indirection you want to keep
    # in your program.
    collection = WordsCollection()
    collection.add_item("B")
    collection.add_item("A")
    collection.add_item("C")

    print("Straight traversal:")
    print("\n".join(collection))
    print("")

    print("Reverse traversal:")
    print("\n".join(collection.get_reverse_iterator()), end="")

Output.txt: 执行结果

Straight traversal:
A
B
C

Reverse traversal:
C
B
A

迭代器在其他编程语言中的实现

C# 迭代器模式讲解和代码示例 C++ 迭代器模式讲解和代码示例 Go 迭代器模式讲解和代码示例 Java 迭代器模式讲解和代码示例 PHP 迭代器模式讲解和代码示例 Ruby 迭代器模式讲解和代码示例 Rust 迭代器模式讲解和代码示例 Swift 迭代器模式讲解和代码示例 TypeScript 迭代器模式讲解和代码示例