Home > Article > Backend Development > How to use the __iter__() function in Python to define the iterability of objects
How to use the __iter__() function in Python to define the iterability of an object
In Python, an iterable object refers to an object that can be traversed through an iterator . For an object to become an iterable object, its class must implement the __iter__() function. This function returns an iterator object that implements the __next__() method.
The basic format of the __iter__() function is as follows:
def __iter__(self): # 返回一个迭代器对象 return self
The following is an example to demonstrate how to use the __iter__() function to define the iterability of an object.
class FibonacciSequence: def __init__(self, n): self.n = n self.a, self.b = 0, 1 self.count = 0 def __iter__(self): # 返回一个迭代器对象 return self def __next__(self): if self.count < self.n: self.a, self.b = self.b, self.a + self.b self.count += 1 return self.a else: raise StopIteration n = int(input("请输入斐波那契数列的长度:")) fib = FibonacciSequence(n) print("斐波那契数列前", n, "个数字为:") for num in fib: print(num)
In the above example, we defined a class called FibonacciSequence to generate the Fibonacci sequence. In the class initialization method __init__(), we pass in the parameter n to represent the length of the Fibonacci sequence to be generated. The __iter__() function returns an iterator object self, and the iterator object that implements the __next__() method can be traversed using a for loop.
In the __next__() method, we use self.count to record the length of the currently generated Fibonacci sequence (that is, the number of numbers that have been returned), when self.count is less than n , we generate the next number according to the rules of the Fibonacci sequence, assign self.b to self.a, assign the sum of self.a and self.b to self.b, and add 1 to self.count. When self.count is equal to n, we throw a StopIteration exception, which is the end mark of the iterator.
Finally, in the main program, we instantiate a FibonacciSequence object fib by inputting the value of n, pass it into the for loop to traverse, and print out the first n of the Fibonacci sequence one by one number.
Through the above example, we can see how to use the __iter__() function to define the iterability of an object. As long as an object implements the __iter__() function and returns an iterator object that implements the __next__() method, you can use for loops and other methods to iterate through it. This method allows our custom objects to be traversed like Python's built-in lists, dictionaries and other objects.
The above is the detailed content of How to use the __iter__() function in Python to define the iterability of objects. For more information, please follow other related articles on the PHP Chinese website!