Generator expression Form
Directly on the code
1 # Yield expression Form 2 def foo (): 3 print (' starting ') 4 while True:5 X=yield #默认返回为空, actually x=yield None 6 p Rint (' value ', x) 7 G=foo () 8 Print (g.__next__ ()) #停到yield位置, generator initialized, encountered yield returns a none 9 print ('---Split line June---') print ( G.send (1)) #传值给yield, then yield to X, and last trigger once next, encounter yield returns a value of None and pauses print ('---Split line June---') print (G.send (2))
Output results
1 starting2 None #运行g. __next__ () return value 3---Split line June---4 value 1 #运行g. Send (1) Print 5 None #运行g. Send (1) return value, returned by yield 6---split line June---7 value 2 #运行g. Send (2) Print 8 None #运行g. Send (2) return value
The expression form of the generator, after each function that contains the form of the generator expression, must be executed after the first __next__ method is initialized (that is, the default return value of None is passed in) before the value can be passed in using the Send () method, or a TypeError error is thrown.
Initialize adorner: Use the adorner decoration method to perform the yield initialization operation after function definition to prevent forgetting
def init_generator (func): def generator (*args,**kwargs): gen=func (*args,**kwargs) next (gen) Return Gen return generator
Process-oriented programming
Function of the parameters passed in, is the function eat food, and function Return/yield return value, is the result of the function pull out, the process-oriented idea is that the execution of the program as a string of functions, a function to eat, pull things to another function to eat, Another function eats and then continues to pull to the next function to eat ...
Application: Recursive folder of a directory, determine whether the contents of the directory and subdirectories within the content of the file contains the specified string, if there is the absolute path of the file to print out
Analysis:
Phase one: Recursively find the absolute path of the file, send the path to phase two
Stage Two: Receive file path, open file Get object, send file object to phase three
Phase three: Receive the file object, for loop read each line of the contents of the file, send each line of content to phase four
Phase four: Receive a line of content to determine if root is in this row, if so, then send the file name to stage five
Phase five: Receive file name, print results
1 #应用: Grep-rl ' root '/etc 2 import OS 3 def init (func): 4 def wrapper (*args,**kwargs): 5 G=func (*args,**kwar GS) 6 Next (g) 7 return G 8 return wrapper 9 #阶段一: Find the absolute path of the file recursively, send the path to phase 210 @init11 def search: 12 ' Search file Abspath ' while true:14 start_path=yield15 g = Os.walk (Start_path) + for par _dir, _, files in g:17 # print (par_dir,files) with file in files:19 File_path = r '%s\%s '% (par_dir, file) target.send (File_path) #阶段二: Receive file path, open file Get object, send file object to phase 322 @init23 def opene R (Target): "Get file Obj:f=open (filepath) ' while true:26 file_path=yield27 with open (File_pat h,encoding= ' Utf-8 ') as F:28 target.send ((file_path,f)) #阶段三: Receives the file object, for loop reads each line of the file content, sends each line content to the stage 431 @init32 def cat (target): true:35 ' read file ' and ' filepath,f=yield36 ' in f:37 Res =target.send ((filepath,lINE) if res:39 break40 #阶段四: Receive a line to determine if root is in this line, and if so, send the file name to stage 542 @init43 def grep (targe T,pattern): "grep function" tag=false46 while true:47 filepath,line=yield tag #target. Send (Filepa Th,line)) tag=false49 if pattern in line:50 target.send (filepath) Wuyi tag=true52 # Phase five: Receive file name, print result @init54 def printer (): "Print function" and "true:57" filename=yield58 print ( FileName) start_path1=r ' C:\Users\Administrator\PycharmProjects\python5 period \a ' start_path2=r ' C:\Users\ Administrator\pycharmprojects\python5 period \a\b ' G=search (Opener (grep (printer (), ' root '))) and print (g) 65 # G.send (start_path1) g.send (start_path2)
Built-in functions
abs () function: returns the absolute value of a number
Grammar:
1 abs (x) #x--Numeric expression
Example:
Print (ABS ( -9)) print (ABS (5.5)) print (ABS (45))
All () function: Determines whether all elements in the given iteration parameter iterable are not 0, ', false, or iterable null, and returns FALSE if True
Grammar:
1 All (iterable) #iterable元组或列表
Example:
1 All ([' A ', ' B ', ' C ', ' d ']) # list, the element is not empty or 0, the result returns True2 all ([' A ', ' B ', ', ' d ') # list, there is an empty element, the result returns False3 AL L ([0, 3]) # list, there is an element of 0, the result returns FALSE4 all ((' A ', ' B ', ' C ', ' d ')) # tuple tuple, the element is not empty or 0, the result returns True5 all (' A ', ' B ', ' ', ' d ') # tuple, there is an empty element, the result returns FALSE6 all ((0, 3)) # Tuple tuple, there is a 0 element, the result returns FALSE7 all ([]) # empty list, The result returns True8 all (()) # Empty tuple, the result returns True
Any () function: Determines whether the given iteration parameters iterable are all empty objects, returns False if all are empty, 0, false, or True if not all null, 0, False
Grammar:
1 any (iterable) #iterable元组或列表
Example:
1 any ([' A ', ' B ', ' C ', ' d ']) # list, elements are not empty or 0, results return True2 any ([' A ', ' B ', ' ', ' d ']) # list, there is an empty element, the result returns TRUE3 any ([0, ', False]) # list, the element is all 0, ', false, the result returns FALSE4 any ((' A ', ' B ', ' C ', ' d ')) # Tuple tuple, the element is not empty or 0, the result returns True5 any ((' A ', ' B ', ', ' d ')) c4/># tuple, there is an empty element, the result returns True6 any ((0, ", False)) # Tuple, the element is all 0,", False, the result returns FALSE7 any ([]) # empty list, The result returns False8 any (()) # Empty tuple, and the result returns false
binary Conversion functions: decimal to Binary bin (), Decimal to octal Oct (), Decimal to hex hex ()
Grammar:
1 bin (x) 2 Oct (x) #x为int或者long int 3 hex (x)
Example:
1 Bin (3) 2 Oct (9) 3 Hex (13)
bool () function: boolean value using constant true and false to denote
Grammar:
1 bool (x) #x为任意值
Example:
BOOL (0) #Falsebool ("abc") #Truebool ("") #Falsebool ([]) #Falsebool () #False
bytes () function: Returns a new non-modifiable byte array
Grammar:
1 #常用2 bytes (string,encoding)
Example:
1 print (bytes (' sss ', encoding= ' Utf-8 ')) 2 #等同于下面3 print (' SSS '. Encode (' Utf-8 '))
Help () function: The function is used to view a detailed description of the function or module's purpose.
Grammar:
1 Help (X)
Example:
Help (' sys ') # View the SYS module's assistance helps (' str ') # View the str data type Help (a) # View list Help information
callable () function: used to check whether an object is callable. If return true,object still may fail, but if return false, calling object Ojbect will never succeed. For functions, methods, lambda functions, classes, and class instances that implement the __call__ method, it returns TRUE.
Grammar:
1 Callable (object)
Example:
1 callable (ABS) # function returns True, or the custom function returns True
chr () function: returns a corresponding character, corresponding to the ASCII table, with a range (that is, 0~255) integer within the ranges (256)
Grammar:
1 Chr (i) #i为0-255 digits, which can make 10 binary or 16-binary
Example:
1 Chr (0x30) #返回02 chr #返回B
Ord () function: Chr () function's pairing function, Chr () incoming number returns corresponding character, Ord () incoming character returns number
Grammar:
1 ord (c) #c为字符, can only be a
Example:
Ord (' B ') #返回66ord (' 1 ') #返回49
Complex () function: Used to create a complex number with a value of real + Imag * J or to convert a string or count to a plural. If the first argument is a string, you do not need to specify a second argument
Grammar:
1 complex ([real[, Imag]]) 2 real--int, long, float or string 3 imag--int, long, float
Example:
1 x=1-2j #等同于x =complex (1-2j) 2 print (x.real) #显示实部3 print (X.IMAG) #显示虚部
int () function : Used to convert a string to an integral type
Syntax: slightly
Example: slightly
dict () function: used to create a dictionary
Syntax: slightly
Example: slightly
tuple () function: convert a list, dictionary, or collection to a tuple
Syntax: slightly
Example: slightly
list () function: used to convert a tuple, dictionary, or collection to a list
Syntax: slightly
Example: slightly
set () function: Create an unordered set of elements that can be tested for relationships, delete duplicate data, and calculate intersections, differences, and sets.
Syntax: slightly
Example: slightly
str () function: converts an object into a form suitable for human reading.
Syntax: slightly
Example: slightly
dir () function: Returns a list of the variables, methods, and definitions in the current scope without arguments, and returns the properties, methods list of the parameters, with parameters. If the parameter contains method __dir__ (), the method is called. If the parameter does not contain __dir__ (), the method will collect the parameter information to the maximum
Grammar:
1 Dir (object)
Example:
1 Import os2 dir (OS) #显示os模块的可调用方法输出结果 [' Direntry ', ' f_ok ', ' mutablemapping ', ' o_append ', ' o_binary ', ' o_creat ', ' o_excl ', ' o_noinherit ', ' o_random ', ' o_rdonly ', ' o_rdwr ', ' o_sequential ', ' o_short_lived ', ' o_temporary ', ' o_text ', ' O_TRUNC ' , ' o_wronly ', ' P_detach ', ' p_nowait ', ' P_nowaito ', ' p_overlay ', ' p_wait ', ' pathlike ', ' r_ok ', ' seek_cur ', ' seek_end ', ' SE Ek_set ', ' Tmp_max ', ' w_ok ', ' x_ok ', ' _environ ', ' __all__ ', ' __builtins__ ', ' __cached__ ', ' __doc__ ', ' __file__ ', ' __ Loader__ ', ' __name__ ', ' __package__ ', ' __spec__ ', ' _execvpe ', ' _exists ', ' _exit ', ' _fspath ', ' _get_exports_list ', ' _ Putenv ', ' _unsetenv ', ' _wrap_close ', ' abc ', ' Abort ', ' access ', ' altsep ', ' chdir ', ' chmod ', ' close ', ' closerange ', ' Cpu_co Unt ', ' curdir ', ' defpath ', ' device_encoding ', ' devnull ', ' dup ', ' dup2 ', ' environ ', ' errno ', ' Error ', ' execl ', ' execle ', ' E XECLP ', ' execlpe ', ' execv ', ' execve ', ' execvp ', ' execvpe ', ' extsep ', ' fdopen ', ' fsdecode ', ' fsencode ', ' fspath ', ' Fstat ', ' Fsync ', ' ftruncate ', ' get_exec_path ', ' geT_handle_inheritable ', ' get_inheritable ', ' get_terminal_size ', ' getcwd ', ' getcwdb ', ' getenv ', ' getlogin ', ' getpid ', ' Getppid ', ' isatty ', ' kill ', ' linesep ', ' link ', ' listdir ', ' lseek ', ' lstat ', ' makedirs ', ' mkdir ', ' name ', ' Open ', ' pardir ', ' Path ', ' pathsep ', ' pipe ', ' popen ', ' putenv ', ' read ', ' Readlink ', ' Remove ', ' removedirs ', ' Rename ', ' Renames ', ' replace ', ' RmDir ', ' scandir ', ' Sep ', ' set_handle_inheritable ', ' set_inheritable ', ' spawnl ', ' Spawnle ', ' spawnv ', ' spawnve ', ' St ', ' Startfile ', ' stat ', ' stat_float_times ', ' stat_result ', ' statvfs_result ', ' strerror ', ' Supports_bytes_environ ', ' Supports_dir_fd ', ' supports_effective_ids ', ' supports_fd ', ' supports_follow_symlinks ', ' symlink ', ' sys ', ' system ', ' Terminal_size ', ' Times ', ' times_result ', ' truncate ', ' umask ', ' uname_result ', ' unlink ', ' urandom ', ' utime ', ' waitpid ', ' Walk ', ' write ']
Python foundation------Builder Expression form, process-oriented programming, built-in function section