Python generator decorator closure iterator metaclass gil log coroutine garbage collection descriptor property

Iterators and Generators

In Python, an iterator (Iterator) is a way to iterate through a collection of data, and you can access the elements in the collection one by one without loading the entire collection into memory in advance. Iterators in Python are usually implemented based on iterable objects (Iterable), such as lists, tuples, dictionaries, strings, etc.

A generator (Generator) is a special iterator that can dynamically generate data in each loop instead of generating all data at once. Generators are great for dealing with large amounts of data because they only compute and generate what is needed when necessary, rather than generating all the data at once, which is memory-intensive.

The difference between them is that an iterator is implemented by defining a class, __iter__()and __next__()two methods of and must be implemented. The meaning, usage, and return value of each method need to consider all details when implementing it. The generator is relatively simple, you can use the keyword yieldto generate data, and each time the generator is called, it will automatically yieldcontinue to execute from the previous statement until the generator ends or returnthe statement . In Python, generators are usually defined by functions, for example:

def my_generator(num):
    for i in range(num):
        yield i

This generator function is used to 0generate num - 1integers from to , and the elements in the generator can be accessed through fora loop , for example:

 
 
for item in my_generator(10):
    print(item)

Here my_generator(10)returns a generator object that dynamically generates integers from0 to , looping until the generator ends or a statement is encountered.9return

おすすめ

転載: blog.csdn.net/m0_61634551/article/details/131215753