Python Learning _08_-functional programming

Source: Internet
Author: User

In Python, a function name is also a variable that represents a reference to a function's contents, which means that it can be passed into other functions as a parameter, which, based on this feature, radiates out the concepts of adorners, closures, and other issues such as variable scope.

Function

In Python, the function operation identifier (), which needs to be appended to the function name in any place where the function needs to be called (), means that the function is called, otherwise it simply represents a function object, which can either save the object or pass the function object into another function for deferred invocation.

The parameters of the function are divided into the positional parameters, the default parameters, the non-keyword variable length parameter, and the variable length parameter of the keyword.

Where the positional parameters are only determined by the order in which they are passed in, and if there are no default arguments, the number of arguments passed in must be consistent with the function definition. Python supports default parameters, initializes some common parameters, and avoids repeating the same parameters. Both are the parameter forms of the regular function. Another unconventional parameter is that the number of parameters is not necessarily a variable length parameter, which can be a tuple with no keywords, or a dictionary with keywords.

In Python, a parameter pass-through rule can be represented as follows:

def myFunc ([Formal_args,] *args_tuple,**kw_dict)

where Formal_args represents positional parameters, contains possible default parameters, and *args_tuple represents variable-length non-keyword parameters, **kw_dict represents variable-length keyword parameters.

anonymous function Lambada

An anonymous function is a special use of a single-line statement in Python to simplify some simple functions. Such as

Fun Add (x, y):
? ? Return X+y

You can use Lambada x,y:x+y to represent that, after Lambada, the contents before the colon represent the arguments that need to be passed in, and the contents after the colon represent the single-line statement that executes.

Lambada can be stored so that later calls, such as Add = Lambada x,y:x+y, can be called add (x, y).

Adorner decorator

Because the nature of the function is a reference, so the function name can be passed in, out, and so on, and the general variable operation, through this feature, you can design some adorners, in order to repeat the function of the common operation. There is extra syntax support for adorners in Python: @, adding a @decorator statement above the function, which means that the function is being decorated. A function can be decorated by multiple adorners. The essence of the adorner is the function, so the adorner also supports parameter passing in. An example of an adorner:

def log (func):
? ? Def wrappedfunc ():
? ? ? ? print ' The%s () is called! '% func.__name__
? ? ? ? Return Fun ()
? ? Return Wrappedfunc

Use the adorner in a @log way:

@log
def func ():
? ? Pass

The meaning of the above statement is Func=log (func), at which point the content of the func invokes the adorner Log,log function eventually returns the Wrappedfunc function object, but the function is not called, and when Func () is executed it actually calls Wrappedfunc (), The function first prints a row of call logs and then returns a call to the Func () function, where the call returned is not a Func function object, so the entity of the Func function is actually executed here. So as to achieve the "decoration" process.

Closed Bag closure

After python2.1, the scope rule changes to a static scope, and the intrinsic function can normally refer to the external variable, which refers to the function of an external scope variable called a closure:

def counter (start_at = 0):
? ? Count = Start_at
? ? Def incr ():
? ? ? ? Count + = 1
? ? ? ? return count[0]
? ? Return INCR

Can see the form of the closure of the adorner is very much like, the difference is that the closure of the incoming is not necessarily a function, just a reference to the external variables, internal functions do not necessarily need to execute the incoming function, may do some other work.

An example of closures and adorners:

From time Import time
def logged (when):
? ? def log (F,*args,**kargs):
? ? ? ? print ' called:
Function:%s
Args:%r
Kargs:%r "% (F,args,kargs)

? ? Def pre_logged (f):
????? def wrapped (*args,**kargs):
? ? ? ? ? ? Log (F,*args,**kargs)
? ? ? ? ? ? return F (*args,**kargs)
? ? ? ? return wrapped

? ? Def? Post_logged (f):
? ? ? ? def wrapped (*args,**args):
??????? now = Time ()
??????? Try:
? ? ? ? ? ? ? ? return F (*args,**kargs)
? ? ? ? ? ? Finally
? ? ? ? ? ? ? ? Log (F,*args,**kargs)
? ? ? ? ? ? ? ? Print "Time Delta:%s"% (time ()-now)
? ? ? ? return wrapped

? ? Try
? ? ? ? return {' Pre ': pre_logged, ' post ':p Ost_logged}[when]
? ? Except Keyerror,e:
? ? ? ? Raise ValueError (E), ' must be ' pre ' or ' post '

@logged ("POST")
def hello (name):
? ? Print "Hello,", name

Hello ("word!")?

Partial function

Partial functions can be introduced by referring to partial in the Functools module, where the concept of a partial function is to determine one of the parameters of a function that would otherwise require more than one parameter and call it another function:

From operator import add
From Functools Import Partial
ADD1 = partial (add,1)

At this point, add1 (5) means add (1,5)

Scope and GLOBA statements

When Python searches for an identifier, it starts with a local variable and, if not found, searches from the previous level until it is not found and returns Nameerror

With the Globa keyword, you can roll out a variable to a local scope without referencing a named global variable directly from the lookup process described above.

Generator and yield statements

The generator generates iterators with yield statements, and each yield statement sequentially causes its contents to be called in the next () method:

Def Simplegen ():
? ? Yield 1
? ? Yield 2

At this point, Simplegen () is an iterator, Simplegen (). Next () = 1,simplegen (). Next () = 2

In addition to the next () method, you can also send a value to the generator using the Send method:

def counter (start_at = 0):
? ? Count = Start_at
? ? While True:
? ? ? ? val = (yield count)
? ? ? ? If Val is not None:
? ? ? ? ? ? Count = Val
? ? ? ? else:
??????? count + = 1

Count = Count (5)

Count.next () = 5;count.next () = 6;count.send (9) = 9; Count.next () = ten; Count.close ();? Count.next (): Stopiteration?

Python Learning _08_-functional programming

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.