Python Advanced--01 functional programming

Source: Internet
Author: User
Tags closure define function

1. Concept

Functions: Function, is the method inside the programming

Function: Functional, is a programming paradigm

2. Features

Think of calculations as functions, not directives

Pure functional Programming: No variables required, no side effects, simple testing

Supports higher-order functions with simple code

Functional programming supported by 3.python

Not purely functional programming: allowed variables

supports higher order functions : Functions can be passed in as variables

support Closures : the ability to return functions with closures

Limited support for anonymous functions

4. High-order Function 4.1 concepts

Functions that can receive functions as variables, called higher-order functions

4.2 Principle

The function name in Python is actually a variable .

>>> ABS (-10)

10

>>> Abs=len

>>> ABS (-10)

Traceback (most recent):

File "<pyshell#2>", line 1, in <module>

ABS (-10)

Typeerror:object of type ' int ' has no Len ()

>>> ABS ([+])

3

4.3 examples

>>> def add_ab (x,y,f):

return f (x) +f (y)

>>> Add_ab ( -5,9,abs)

14

5. Return function

>>> def f ():

print ' Call f () ... '

# define function G:

def g ():

print ' call g () ... '

# return function g:

return G

>>> x=f ()

Call F () ...

>>> x

<function G at 0x0000000002f05a58>

>>> x ()

Call G () ...

6. Closure 6.1 Concept

The inner layer function refers to the variable of the outer function ( the parameter of the outer function is also the variable ), and then returns the case of the inner function, called the Closure (Closure).

6.2 Features

The returned function also refers to the local variables of the outer function;

In addition, when the closure is defined, the code inside is not running and only runs the code when it is actually called , so the value of the variable that is taken at runtime is the value of the variable at run time (undefined moment)!!!

Therefore, to properly use closures, it is necessary to ensure that the referenced local variables cannot be changed after the function returns.

IMPORTANT: The default parameter values are obtained at the defining moment!!!

# you want to return 3 functions at a time, calculate 1x1,2x2,3x3 separately:

>>>def count ():

FS = []

For I in range (1, 4):

def f ():

Return I*i

Fs.append (f)

Return FS

F1, F2, F3 = count ()

>>> F1 ()

9

7. Anonymous function 7.1 Example

Lambda x:x * x

is equivalent to

def f (x):
return x * x
7.2 Features:

The keyword lambda represents an anonymous function, and one (more) variable preceding the colon represents the function parameter ;

There can be only one expression, no return, and the return value is the result of the expression .

With anonymous functions, you do not have to define the name of a function

You can also return an anonymous function when returning a function

8. Adorner decorator8.1 background

A function has been defined to dynamically add function functions at run time without having to change the code of the function itself

8.1.1 Changing the source code

>>> def f1 (x):

... print ' Call F1 () '

... return x*2

...

>>> def f2 (x):

... print ' Call F2 () '

... return x*x

...

>>> def f3 (x):

... print ' Call F3 () '

... return x*x*x

8.1.2 returning new functions using higher-order functions

>>> def NEW_FN (f):

... def fn (*args,**kw):

... print ' call%s () '% f.__name__

... return f (*args,**kw)

.. return fn

There are two methods of calling:

8.1.3 automatically generate new functions with the built-in @

Cases

Print log: @log

Detection performance: @performance

Database transactions: @transaction

URL routing: @post ('/register ')

8.1.4 Decorator Concept

Python's decorator is essentially a high-order function that takes a function as an argument and then returns a new function.

8.2 Parameterless Adorner 8.2.1 format

# define non-parametric adorners

Def deco_performance (f):

# define temporary functions in adorners

def tmp (*ARGS,**KW):

# Execute the decorated function, can use parameters with the parametric adorner

# XXX

# Returns the result of being decorated function execution

return result

#return F (*args,**kw)

# returns the name of the temporary function in the adorner

return tmp

8.2.2 Example

# Write a @performance that can print out the time of the function call

def performance (f):

# to make @performance adaptive to any function defined by a parameter, you can take advantage of Python's

# *args and **kw, to ensure that any number of parameters can always be called normally

def tmp (*ARGS,**KW):

Print "Before call-->%s"% (Time.time ())

# now call the decorated function

result = f (*args,**kw)

Print "After call-->%s"% (Time.time ())

# You just need to return the function result, not necessarily return F (*args,**kw)

return result

# just return the function name

return tmp

# @performance Use

@performance

def factorial (n):

return reduce (lambda x,y:x*y, range (1, n+1))

# calls to functions decorated with @performance

Print factorial (10)

8.3 Parametric Adorner 8.3.1 format

# define a parametric decorator

def performance (unit):

# define non-parametric adorners

Def deco_performance (f):

# define temporary functions in adorners

def tmp (*ARGS,**KW):

# Execute the decorated function, can use parameters with the parametric adorner

# XXX

# Returns the result of being decorated function execution

return result

# returns the name of the temporary function in the adorner

return tmp

# returns the name of the non-parametric adorner

Return deco_performance

8.3.2 Example

# define a parametric decorator

def performance (unit):

# define non-parametric adorners

Def deco_performance (f):

# define temporary functions in adorners

def tmp (*ARGS,**KW):

# Execute the decorated function, can use parameters with the parametric adorner

Print "Before call time-to%f"% (Time.time () if unit== ' s ' Else Time.time () *1000)

Result=f (*ARGS,**KW)

Print "After call time-to%f"% (Time.time () if unit== ' s ' Else Time.time () *1000)

Print "Call%s ()"% (f.__name__)

# Returns the result of being decorated function execution

return result

# returns the name of the temporary function in the adorner

return tmp

# returns the name of the non-parametric adorner

Return deco_performance

# Use a (NO) parameter decorator

@performance (' s ')

def factorial (n):

return reduce (lambda x,y:x*y, range (1, n+1))

# Call a function that uses a (no) parameter adorner

Print factorial (10)

8.4 Decorator Perfect 8.4.1 problem

After the @decorator"transform" function, the new function name returned has been changed , not ' F2 ', but @log internally defined ' wrapper '. This will invalidate the code that relies on the name of the function. Decorator also changes other properties such as __doc__ of the function . If you want the caller to see that a function has undergone a @decorator transformation, it is necessary to copy some of the properties of the original function into the new function.

8.4.2 Perfect method

1. Manually add attributes manually in the temporary function of the adorner

def log (f):

def wrapper (*args, **kw):

print ' Call ... '

Return f (*args, **kw)

wrapper.__name__ = f.__name__

wrapper.__doc__ = f.__doc__

Return wrapper

2. Automatic copy action using Python's built-in Functools adorner

Import Functools

def log (f):

@functools. Wraps (f)

def wrapper (*args, **kw):

print ' Call ... '

Return f (*args, **kw)

Return wrapper

8.4.3 problems that cannot be avoided

Finally, it is necessary to point out that since we have changed the original function signature (*args, **kw), we cannot get the original parameter information of the original function .

9 Partial Function 9.1 concept

A function has been defined that has too many arguments for the function to dynamically reduce the parameters that the function must enter at run time , making it simpler to invoke and implementing the same functions as the default parameters , without altering the original function .

9.2 examples

>>> int (' 12345 ')

12345

>>> int (' 12345 ', 8)

5349

>>> Int2 = functools.partial (int,base=2)

>>> int2 (' 1111 ')

15

9.3 Note

when you create a partial function , you can actually receive the 3 parameters of the function object, *args, and **kw, if the parameter passed in the Xx=xx type, represents the incoming KW, and if the parameter passed into the type xx is automatically added to the parameter tuple as args, Be aware of whether the original function should have results.

>>> Max (3,4,5)

5

>>> max2 = functools.partial (max,10)

>>> Max2 (3,4,5)

10

Python Advanced--01 functional programming

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.