SoFunction
Updated on 2025-03-02

Advanced python custom iterable classes

Custom iterable classes

A list can get the length of the list, and then loop through the list index using the variable i, or it can also get all elements of the collection, which is easy to understand. Yes, the code using lists is easy to understand and easy to operate, but it comes at a price. The reason why a list can be quickly positioned with indexes is because the list loads all data in memory at once, and it is a continuous piece of memory space. When the data volume is relatively small, it is easier to implement; when the data volume is very large, it will consume very much memory resources. Iteration is different. Iteration is to load the number of elements into memory if it reads, and not load it if it does not read. This is a bit like two ways to deal with XML: DOM and SAX. DOM loads all XML data into memory at once, so it can quickly locate any element, but the cost is to consume memory; while SAX reads XML documents sequentially, and the content of the XML document that has not been read will not be loaded into memory, so SAX saves memory, but can only read the content of the XML document from front to back.

If defined in a class__iter__Method, then an instance of this class is an iterator.__iter__The method needs to return an iterator, so it can return the object itself (that is, self). When the object is iterated once, another special member method in the iterator is called__next__ . This method needs to return the results of the current iteration. Let's first look at a simple example, in which asterisks are paired with a custom iterator.*Each row of the formed straight triangle is iterated, and then iterates through a for loop to output a right triangle with a certain number of rows.

# Iterate infinitely through rows of right trianglesclass righttriangle:
  def __init__(self):
    # Define a variable n to represent the current number of rows     = 1
  def __next__(self):
    # Get the string of each line of a direct triangle by multiplication, the length of each line of the string is 2 * n -1    result = '*' * (2 *  - 1)
    # Add 1 to row count     += 1
    return result
  # This method must return an iterator  def __iter__(self):
    return self

rt = righttriangle()
# Iterate over the iteratorfor e in rt:
  # Limit the length of the output line cannot be greater than 20, otherwise the output line will be infinite.  if len(e) > 20:
    break
  print(e)

Output result:

*
***
*****
*******
*********
***********
*************
***************
*****************
*******************

[Example 10.10] Let’s take a more interesting example, in which an iterator class (Fibonacci) is defined for unlimited iteration of Fibonacci sequences.

# Can iterate the Fibonacci sequence without limitclass Fibonacci:
  # Define two variables a and b in the construction method to represent the two values ​​of the Fibonacci sequence  def __init__(self):
     = 0
     = 1
  def __next__(self):
    # is the value to be iterated    result = 
    # Calculate the next value of the Fibonacci sequence and turn a into the original b and turn b into the next value    ,  = ,  + 
    # Return the value of the current iteration    return result
  # This method must return an iterator  def __iter__(self):
    return self

fibs = Fibonacci()
# Iterate over the Fibonacci sequencefor fib in fibs:
  print(fib,end = ' ')
  # The value of iteration cannot exceed 500  if fib > 500:
    break

Output result:

0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 

The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.