Decorator
#Decorative ring without parameters def decorator(func): def inner(*args, **kwargs): print(1111122221111111) # func(*args, **kwargs) return fun(*args, **kwargs) return inner #Decorators with parameters will have more nesting def outside(arg): def decorator(func): def inner(*args, **kwargs): print(1111122221111111) # func(*args, **kwargs) return fun(*args, **kwargs) return inner return decorator
generator
Generator is a special program, which can be used to control the iterative behavior of loops. In python, generator is a kind of iterator, using yield return value function, each time yield is called, it will pause, and next() function and send() function can be used to recover the generator.
Application scenario: if a large list is generated, it will take up a lot of memory. At the same time, we don't need to read all the data at once, just to read the data in the first few lines in order, so we can use the generator at this time.
The key to the generator's ability to iterate is that it has the next() method, which works by repeatedly calling the next() method until an exception is caught.
lis = [x*x for x in range(10)]
print(lis)
generator_ex = (x*x for x in range(10))
print(generator_ex) [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
<generator object <genexpr> at 0x000002A4CBF9EBA0>
lis Is an iterative object
generator_ex For the generator is also an iterative object
Iterators and substitutable objects iter ()
An object that can be called by the next() function and constantly returns the next value is called an Iterator: Iterator
s='hello' #Strings are iteratable objects, but not iterators
l=[1,2,3,4] #Lists are iteratable objects, but not iterators
t=(1,2,3) #Tuples are iteratable objects, but not iterators
d={'a':1} #Dictionaries are iterative objects, but not iterators
set={1,2,3} #A collection is an iteratable object, but not an iterator
f=open('test.txt') #Files are iteratable objects, but not iterators
#How to judge whether it is an iterative object, only the iterator method, the iterator object obtained by executing the method.
# And iteratable objects are transformed into iterator objects by ﹣ iter ﹣
from collections import Iterator #iterator
from collections import Iterable #Iteratable object
print(isinstance(s,Iterator)) #Judge whether it is an iterator
print(isinstance(s,Iterable)) #Judge whether the object can be iterated
#Convert an iteratable object to an iterator
print(isinstance(iter(s),Iterator))
Reference articles https://www.cnblogs.com/wj-1314/p/8490822.html