Python fifth day: Co-process, anonymous function, recursive function, module import, re module

Source: Internet
Author: User
Tags closure

previous section Review Function Object

Functions can be passed as data

def func ():

Pass

1. can be referenced. F=fun

2. can be passed as a parameter to another function

3. can be used as the return value of a function

4. elements that can be used as container types

For example, the user has more than one parameter, we do not need to write more than one if judgment. Can write a dictionary.

DiC = {' func1 ': func1, ' Func2 ': Func2}

call time with dic[' func1 '] ()

Nesting of functions

the nesting of functions can be divided into two types: nested definitions and nested invocations.

Nested calls: functions that call other functions during the execution of a function can be more granular.

nested definitions (when defining a function, other functions are defined with the DEF keyword): We can use it in the closure function and the decorator.

Namespaces and Scopes

built-innamespaces ( This space is defined by the PY interpreter running)

Global Namespace (defines this space when the file executes, and other file calls need to import this variable)

Local namespaces (when functions are called, they are freed when the function is executed)

global scope: Globally valid, can be accessed at any location, surviving until the end of file execution.

Local scope: Locally valid, can only be accessed within the function, after the execution of the function is finished, it is released.

closure function

is a function defined inside the function, not affected by the external variables, call the outside function, directly return the closure function object.

Def f1 ():

def f2 ():

Print (x)

return F2

F=F1 ()

F ()

Decorative Device

The function is open to the extension and is closed for modification. In order to satisfy this feature, the decorator is used.

The adorner itself can be any callable object and can be decorated with any callable object.

The principle to be followed by the adorner:

1. Do not modify the source code of the object being decorated

2. Do not modify the calling method of the decorated object (including return value, parameter)

iterators

Iteration: Repeats the last procedure, and each repetition continues based on the results of the last execution.

an Iterative object: A __iter__ method is called an iterative object.

Iterator object: an iterator object that has the __next__ method.

Why you have iterators: provides an iterative approach that does not depend on an index.

Pros and cons of iterators: Provide an iterative approach that does not depend on the index, saving memory.

Cannot get length, one-time, can only take next.

Generator

The function Body contains the yield keyword, the result of which the function executes is the generator.

The generator is essentially an iterator, so the yield function is:

1. Make the execution result of the function an iterator.

2.yield is equivalent to the ability to write multiple return within a function .

3. The generator can assign a value to yield by means of the Send method , and then yield and then assign a value to the other variable.

like Num=yield 3.

Y=x.send(ten)

that num is ten, andy is 3.

Course Content co-process function

The co-function is the transfer of parameters to the generator, allowing each iteration to pass different results according to this parameter.

Yield can incoming a value to a function.

Def eater (name):

Print ("Ready to eat"%name)

While True:

Food = yield

Print ("Start to eat"%food)

G=eater (' Alex ')

Next (g)

G.send (' Apple ')

The start of the generator must be transferred NONE.

an adorner can be used to generate a message that does not need to be transmitted NONE of the.

def zhuangshi (fun):

def fun1 (*args,**kwargs):

F = Fun (*args,**kwargs)

F.send (None)

return F

Return FUN1

@zhuangshi

Def eater (name):

Print ("Ready to eat%s"%name)

Food_list=[]

While True:

Food_list.append (food)

Food = yield Food_list

Print ("%s start to eat%s"% (Name,food))

G=eater (' Alex ')

G.send (' apple ')

conclusion:yield not only has return function, but also can pass the parameter to him through the shengcheng.send () function. You can also return the value after yield.

process-oriented programming approach

1. write a program that can be returned and

Os.walk Usage

Pass in a directory and return a tuple with 3 elements. (Parent directory, sub-directory list, sub-file list)

It then executes walk recursively on its subdirectories , returning multiple tuples.

This is similar to the case:

we can write multiple function generators to nest with each other: Find file name → open file → find line → judge row → print file name the process of writing a similar program to GREP-RL .

This kind of program is a kind of pipeline-like programming idea, is the mechanical type.

Advantages: The program structure is clear, can simplify the complex problem. The disadvantage is poor scalability, reaching.

anonymous function lambda

We put the function

def f1 (x, y):

Z=x+y

Return Z

rewrite it as an anonymous function , first replacing the def with a lambda , removing F1(), and the function body and return replaced by : , you will Z written X+y .

Lambda X,y:x+y

some built-in that can use anonymous functions

Map:map

Reduce

Filter

Max(salaries,key=func): passes the previous result to the subsequent function as a parameter, and then compares the returned result to Max . However, the type of the returned value is the type of the value preceding the direct max.

Higher order function: if one of the functions is a function, or a function is returned, then he is the higher order function.

Map: Transfer two parameters, the first parameter is a function object, after you are an iterative object.

Map (Lambda x:x+ ' sb ', list)

He will pass the object after the for loop, then to the previous fun, and then he will insert the processed stuff into the new map object (which can be understood as a list). Finally, the MAP function is returned.

Reduce: Pass three parameters, function, can iterate object, initial value.

If you do not give the initial value, he will iterate over the first value of the object as the initial value, and then iterate over things, assign him and the initial value to the previous function to get the result as the result and continue the iteration of things to operate.

Filter: Pass two parameters, the first parameter? A function, the second argument is an iterative object.

Filter (Lambda x:x.endswith (' SB '), L)

Recursive functions: The function itself is called directly or indirectly during the invocation of a function, which is the recursive invocation of the function.

Python has a recursive lock. The default is to recursively tier

can be used

To set.

Recursive functions are divided into two processes: recursion and backtracking.

Considerations for recursion:

1. Recursion must have a definite end condition.

2. Each time a deeper level of recursion is reached, the problem size should be reduced compared to the previous recursion.

3. recursive efficiency is not high, in Python, too many recursive layers can cause stack overflow.

Recursive applications:

Two-part method

Modules: self-with modules, their own modules, third-party modules.

How to use the module:

1. Import

2.

What the import module does:

1. Create a new namespace

2. Execute the code of the file with the new namespace as the global namespace

3, got a module name, pointing to the spam.py.

There is also a way to import:

From import

This is also a module import:

1. Create a new namespace.

2. Execute the code of the file with the new namespace as the global namespace.

3. directly get the name of the namespace generated by spam.py

4. conflicts with the current file's variables

The from import is a little more convenient than the import call.

The method to execute the import, or the variable of the original file, whichever is the same.

From spam import * ( Import all variables directly )

directly import all the defined variables within the __ALL__ list inside the module .

__name__: As a script execution, his value is __main__, which is __name__=spamwhen the module is imported .

So the general file is at the bottom.

This is to be used as a module to import the time will not be executed, and their own test module can be in the following.

Search path for import:

first find the memory → then find the built-in → then find sys.path.

we can add sys.path things by ourselves.

Sys.path.insert (0,r ' C: \ ... ')

To import a package:

1. either import or from...import form, everything in the import statement encountered with points, it is necessary to know that this is about the package has the import syntax.

The left side of the point must be a package, and on the right there may be a package or a module.

Import package is equivalent to importing the glance under the __init__.py

the call to the package is equivalent to the init file under the swap .

Absolute Import: When importing a package under Glance under __init__ use from glance.xx import xxx

this and glance -level files, you can find this package directly.

From.. DB Import xxxx

From ... db import xxx

The relative path is used in order to facilitate the problem of package name changes later.

* Special use of

You can import modules directly. This is another use.

RE module:

importing re modules,importre

Regular online Debugging tools:tool.oschina.net/regex/

Re.findall (PARTTEN,STR)

Metacharacters

\w: Matches alphanumeric and underscore.

. can match any character, but cannot match line break \ n

[]: Matches any one of these characters, can match \ n.

in here ? It means escaping, not. 0-1 times, the greedy match is converted to a non-greedy match.

| :

If the match succeeds, only the contents of the parentheses are returned.

It would be nice to escape.

The following example is the same:

Python fifth day: Co-process, anonymous function, recursive function, module import, re module

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.