Learn the Python function notes

  • 2020-05-07 19:54:31
  • OfStack

  definition
Returns a single value


def my_abs(x):
  if x >= 0:
    return x
  else:
    return -x
 

returns the multivalue

To return multiple values is to return 1 tuple


import math
 
def move(x, y, step, angle=0):
  nx = x + step * math.cos(angle)
  ny = y - step * math.sin(angle)
  return nx, ny

empty function
 


def nop():
  pass

specifies the default parameter

The required parameters are first, and the default parameters are last. The default parameter should point to an immutable object (the default parameter value is calculated when the function is defined)
 


def power(x, n=2):
  s = 1
  while n > 0:
    n = n - 1
    s = s * x
  return s

variable parameter
 


def calc(*numbers):
  sum = 0
  for n in numbers:
    sum = sum + n * n
  return sum

calls function methods with variable arguments
 


>>> calc(1, 2)
5
>>> calc()
0
>>> nums = [1, 2, 3]
>>> calc(*nums)
14

keyword parameter
 


def person(name, age, **kw):
  print 'name:', name, 'age:', age, 'other:', kw

calls methods for keyword arguments
 


>>> person('Michael', 30)
name: Michael age: 30 other: {}
>>> person('Bob', 35, city='Beijing')
name: Bob age: 35 other: {'city': 'Beijing'}
>>> person('Adam', 45, gender='M', job='Engineer')
name: Adam age: 45 other: {'gender': 'M', 'job': 'Engineer'}
>>> kw = {'city': 'Beijing', 'job': 'Engineer'}
>>> person('Jack', 24, **kw)
name: Jack age: 24 other: {'city': 'Beijing', 'job': 'Engineer'}

Note:

The order in which       parameters are defined must be: required parameters, default parameters, variable parameters, and keyword parameters.
For any function, it can be called in a form similar to func(*args, **kw), regardless of how its arguments are defined.

recursive

If a function calls itself internally, it is a recursive function.
tail recursion

When the function returns, it calls itself, and the return statement cannot contain an expression.
higher order function

      variables can point to functions (functions can be assigned to 1 variable)       function names are also variables (function names can be assigned to other values) The       function can be used as an argument to a function (higher-order function)

map(func, list)

The map() function takes two arguments, one a function and one a sequence, and map applies the incoming function to each element of the sequence in turn, returning the result as the new list.
 


>>> def f(x):
...   return x * x
...
>>> map(f, [1, 2, 3, 4, 5, 6, 7, 8, 9])
[1, 4, 9, 16, 25, 36, 49, 64, 81]
reduce(func_with_two_params, list)

reduce applies 1 function to 1 sequence [x1, x2, x3...] Above, this function must take two arguments, reduce continues the cumulative calculation with the next element of the sequence.
 


reduce(f, [x1, x2, x3, x4])
# Is equivalent to: 
f(f(f(x1, x2), x3), x4)
 
>>> def add(x, y):
...   return x + y
...
>>> reduce(add, [1, 3, 5, 7, 9])
25

filter(func_return_bool, list)

The incoming function is applied to each element in turn, then the element is retained or discarded depending on whether the return value is True or False.
 


import math
 
def move(x, y, step, angle=0):
  nx = x + step * math.cos(angle)
  ny = y - step * math.sin(angle)
  return nx, ny
0

sorted

For the two elements x and y, if x is considered < y, returns -1, if you think x == y, returns 0, if you think x > y returns 1,
 


import math
 
def move(x, y, step, angle=0):
  nx = x + step * math.cos(angle)
  ny = y - step * math.sin(angle)
  return nx, ny
1

higher order function usage
 


import math
 
def move(x, y, step, angle=0):
  nx = x + step * math.cos(angle)
  ny = y - step * math.sin(angle)
  return nx, ny
2

The return value is the function
 


def lazy_sum(*args):
  def sum():
    ax = 0
    for n in args:
      ax = ax + n
    return ax
  return sum
 
>>> f = lazy_sum(1, 3, 5, 7, 9)
>>> f
<function sum at 0x10452f668>
>>> f()
25

Note: each call to lazy_sum() returns a new function, even if the same argument is passed in.
closure
 


import math
 
def move(x, y, step, angle=0):
  nx = x + step * math.cos(angle)
  ny = y - step * math.sin(angle)
  return nx, ny
4

The reason is that the loop is already executing when count is called, but f() is not executing until the time of the call. So the return function does not refer to any loop variables or variables that will change later.
anonymous function (lambda expression)
 

Is equivalent to:
 


import math
 
def move(x, y, step, angle=0):
  nx = x + step * math.cos(angle)
  ny = y - step * math.sin(angle)
  return nx, ny
5

The keyword lambda represents the anonymous function, and x before the colon represents the function parameter.
The anonymous function is used as the return value
 


import math
 
def move(x, y, step, angle=0):
  nx = x + step * math.cos(angle)
  ny = y - step * math.sin(angle)
  return nx, ny
6

decorator (@func)

The way that functionality is added dynamically during code runs is called "decorator" (Decorator), and decorator is essentially a higher-order function of a return function.
 


import math
 
def move(x, y, step, angle=0):
  nx = x + step * math.cos(angle)
  ny = y - step * math.sin(angle)
  return nx, ny
7

Parse: first execute log('execute'), return the decorator function, then call the returned function, parameter is now function, return the value is wrapper function.

__name__
Since the function s s 228en__ has been changed, the code that depends on this will fail. So functools.wraps.
 

import functools
 
def log(func):
  @functools.wraps(func)
  def wrapper(*args, **kw):
    print 'call %s():' % func.__name__
    return func(*args, **kw)
  return wrapper
 
# For the argument function 
 
import functools
 
def log(text):
  def decorator(func):
    @functools.wraps(func)
    def wrapper(*args, **kw):
      print '%s %s():' % (text, func.__name__)
      return func(*args, **kw)
    return wrapper
  return decorator
partial function (fixed function default)
 

import math
 
def move(x, y, step, angle=0):
  nx = x + step * math.cos(angle)
  ny = y - step * math.sin(angle)
  return nx, ny
9

This is equivalent to specifying the first parameter for the max function
 


max2(5, 6, 7)
 
# Is equivalent to: 
 
max(10, 5, 6, 7)


Related articles: