Python雜項(xiàng)

  • iterator和iterable
    • 如果需要對(duì)象可以作為 for in關(guān)鍵字或者join函數(shù)的參數(shù),需要這個(gè)對(duì)線是一個(gè)可迭代對(duì)象即這個(gè)對(duì)象是iterable的
    • python中可迭代對(duì)象(如list, str, dict, generator)是實(shí)現(xiàn)了 iter方法的對(duì)象,iter方法返回一個(gè)iterator(即實(shí)現(xiàn)了next方法的對(duì)象)
          """
          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._position = -1 if reverse else 0
    
              def __next__(self):
                  """
                  The __next__() method must return the next item in the sequence. On
                  reaching the end, and in subsequent calls, it must raise StopIteration.
                  """
                  try:
                      value = self._collection[self._position]
                      self._position += -1 if self._reverse else 1
                  except IndexError:
                      raise StopIteration()
    
                  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:
                  self._collection = collection
    
              def __iter__(self) -> AlphabeticalOrderIterator:
                  """
                  The __iter__() method returns the iterator object itself, by default we
                  return the iterator in ascending order.
                  """
                  return AlphabeticalOrderIterator(self._collection)
    
              def get_reverse_iterator(self) -> AlphabeticalOrderIterator:
                  return AlphabeticalOrderIterator(self._collection, True)
    
              def add_item(self, item: Any):
                  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("First")
              collection.add_item("Second")
              collection.add_item("Third")
    
              print("Straight traversal:")
              print("\n".join(collection))
              print("")
    
              print("Reverse traversal:")
              print("\n".join(collection.get_reverse_iterator()), end="")
    
    
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容