Python 3 functional programming: anonymous function, higher-order function, decorator

Posted by NickG21 on Tue, 11 Feb 2020 13:42:57 +0100

1, Anonymous function

1. Definition: function name does not need to be defined when defining function

2. Specific examples:

#Ordinary function

def add(x,y):
 
    return x + y

#Anonymous function

lambda x,y: x + y

Call anonymous function:

f = lambda x,y: x + y    #Call after assignment
 
print(f(1,2)

In lambda (i.e. later), only simple expression operations can be performed, and assignment operations cannot be performed.

2, Ternary expression

Format: the result returned when the condition is true if the condition determines that else is false

x = 2
 
y = 1
 
r = x if x > y else y
 
print(r)
 
#2

Ternary expressions are widely used in lambda.

Three.map class

1. Definition: Map (function, sequence), pass all the values in the sequence to the function in turn and accept the returned results in turn to form a list.

It's actually a function mapping.

2. Square:

list_x = [1,2,3,4,5,6,7,8]
 
 
def square(x):
 
    return x * x
 
 
r = map(square,list_x)
 
print(list(r))
 
#[1, 4, 9, 16, 25, 36, 49, 64]

4, map and lambda

Combine map and lambda functions:

 1

list_x = [1,2,3,4,5,6,7,8]
 
r = map(lambda x: x * x,list_x)
 
print(list(r)

2 accept multiple parameters:

list_x = [1,2,3,4,5,6,7,8]
 
list_y = [1,2,3,4,5,6,7,8]
 
r = map(lambda x,y: x * x + y,list_x,list_y)
 
print(list(r))

Note: if the number is not equal, no error will be reported, but only the least one can be calculated

Five.reduce

1.

2. Rules of reduce operation: do continuous calculation and call lambda expression continuously.

The function under reduce must have two parameters.

3. example:

from functools import reduce
 
list_x = [1,2,3,4,5,6,7,8]
 
r = reduce(lambda x,y:x + y,list_x)
 
print(r)
 
#36

Operation process: the first two digits are taken initially, and then the calculation results are passed in as x to continue to be taken in sequence:

((((((1 + 2)+3) + 4)+ 5)+6)+7)+8

 

4. Notes:

  • What to do is determined by lambda, not only adding.
  • The last bit can set the initial value, which is calculated in the first calculation:

         eg: r = reduce(lambda x,y:x + y,list_x,10)

 

Six. filter

1.filter can filter out data that does not conform to the rules.

 

2. example:

Exclude elements with data 0:

list_x = [1,0,0,1,0,1,1,0,1]
 
r = filter(lambda x: True if x == 1 else False,list_x)
 
print(list(r))
 
#[1, 1, 1, 1, 1]

Reduced to:

list_x = [1,0,0,1,0,1,1,0,1]
 
r = filter(lambda x: x ,list_x)
 
print(list(r))
 
#[1, 1, 1, 1, 1]

If the return value of filter is true or false, filtering can be completed

 

7, Command programming vs function programming

Command programming involves def if else for

Functional programming involves map reduce filter lambda (operator)

8, Decorator I

import time
 
def f1():
 
    print(time.time())
 
    print('This is a function')
 
 
 
f1()
 
#1532404967.3804688    #Unix timestamp
 
 This is a function

If many functions want to get the function of time:

import time
 
def f1():
 
    print('This is a function')
 
 
def f2():
 
    print('This is a function')
 
 
def print_current_time(func):
 
    print(time.time())
 
    func()

 
print_current_time(f1)
 
print_current_time(f2)

The disadvantage of this requirement change scheme: the requirement of printing time belongs to each function itself, not newly added, and does not reflect the characteristics of the function itself.

This is the problem to be solved by decorators.

Decorator II

To write a decorator:

import time
 
def decorator(func):
 
    def wrapper():
 
        print(time.time())
 
        func()
 
    return wrapper

 
def f1():
 
    print('This is a function')
 
f = decorator(f1)    #f Got it. return Of wrapper
 
f()

Decorator III

Grammar pond:

import time
 
 
def decorator(func):
        def wrapper():
 
        print(time.time())
 
        func()
 
    return wrapper
 
 
 
@decorator    #@Symbol
 
def f1():
 
    print('This is a function')
 
f1()

There is no change in the logic of the call or in the code of the function. It's the meaning of decorators.

@decorator is equivalent to decorating f1().

Decorator IV

1. Decorator with parameter function:

import time
 
def decorator(func):
 
    def wrapper(func_name):
 
        print(time.time())
 
        func(func_name)
 
    return wrapper
 
 
@decorator
 
def f1(func_name):
 
    print('This is a function named' + func_name)
 

f1('test_func')

2. If multiple functions accept different numbers of parameters:

import time
 
def decorator(func):
 
    def wrapper(*args):
 
        print(time.time())
 
        func(*args)
 
    return wrapper
 
@decorator
 
def f1(func_name):
 
    print('This is a function named' + func_name)
 
@decorator
 
def f2(func_name1,func_name2):
 
    print('This is a function named'+func_name1 )
    print('This is a function named'+ func_name2)
 
 
 
f1('test_func')
 
f2('test_func1','test_func2')    #Functions with different number of parameters can be supported

Decorator V

1.*args does not support * * keyword parameter

Keyword parameters are supported:

import time
 
 
 
def decorator(func):
 
    def wrapper(*args,**kw):    #join**kw,More complete
 
        print(time.time())
 
        func(*args,**kw)
 
    return wrapper
 
 
 
@decorator
 
def f1(func_name):
 
    print('This is a function named' + func_name)
 
 
 
@decorator
 
def f2(func_name1,func_name2):
 
    print(func_name1 + func_name2)
 
 
 
@decorator
 
def f3(func_name1,func_name2,**kw):
 
    print(func_name1 + func_name2)
 
    print(kw)
 
 
 
f1('test_func')
 
f2('123','234')
 
f3('123','234',a = 1, b = 2,c = '123')
 
 
 
#1532408656.565761
 
#This is a function namedtest_func
 
#1532408656.5667255
 
#123234
 
#1532408656.5677273
 
#123234
 
#{'a': 1, 'b': 2, 'c': '123'}

2.

def decorator(func):

    def wrapper(*args,**kw):    #join**kw,More complete

        print(time.time())

        func(*args,**kw)

    return wrapper

func(*args,**kw)This form can be called in any way.

Decorator VI

If you want to modify a package unit, you can add a decorator.

It does not need to destroy the code implementation and is easy to reuse.

A function can have multiple decorators.

Functions that need to be authenticated are added for purposes such as specialized decorators.

Topics: Python Lambda Programming Unix