A beginner's notebook for Python functions _python

Source: Internet
Author: User

Defined
Returns a single value

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

Returns multiple values

Return multi-valued is to return a 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
  

Specify default parameters

The required arguments are in the front, and the default arguments are after. The default argument needs to point to an immutable object (the default parameter value is evaluated when the function is defined)

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

Variable parameters

Def calc (*numbers):
  sum = 0 for
  n in numbers:
    sum = SUM + N * n * return
  sum

To invoke a function method of a variable parameter

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

Keyword parameters

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

Methods to invoke keyword parameters

>>> person (' Michael, "
Name:michael age:30 Other: {} >>> person
(' Bob ', city= ' Beijing ')
Name:bob age:35 Other: {"City": ' Beijing '}
>>> person (' Adam ', ' gender= ' M ', job= ' Engineer ')
Name:adam age:45: {' Gender ': ' M ', ' job ': ' Engineer '}
>>> kw = ' City ': ' Beijing ', ' job ': ' Engineer '}< C7/>>>> (' Jack ', **kw)
Name:jack age:24 Other: {' City ': ' Beijing ', ' job ': ' Engineer '}

Note:

The order of the parameter definitions must be: required, default, variable, and key parameters.
For any function, it can be invoked in the form of a similar func (*args, **kw), regardless of how its arguments are defined.

Recursion

If a function calls itself internally, this function is a recursive function.
Tail recursion

The call itself is called when the function returns, and the return statement cannot contain an expression.
Higher order functions

    • Variables can point to functions (functions can be assigned to a variable)
    • Function names are also variables (functions can be assigned other values)
    • Functions can be used as arguments to functions (higher-order functions)

Map (func, list)

The map () function receives two parameters, one is a function, the other is a sequence, and map functions the passed-in function to each element of the sequence and returns the result as a 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 functions a function in a sequence [X1, x2, x3 ...] , this function must receive two parameters, reduce the cumulative calculation of the result and the next element of the sequence.

Reduce (f, [X1, x2, X3, x4])
#相当于: 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 passed function is applied to each element in turn, and the element is persisted or discarded based on whether the return value is true or false.

def is_odd (n): Return
  n% 2 = 1
 
filter (is_odd, [1, 2, 4, 5, 6, 9, ten])
# results: [1, 5, 9, 15]

Sorted

For two elements x and Y, if you think X < Y, then return 1, and if you think x = = y, return 0 and 1 if you think x > Y.

>>> sorted ([5, 9,,])
[5, 9, 12, 21, 36]

Higher order function usage

def reversed_cmp (x, y):
  if x > y:
    return-1
  if x < y: return
    1 return
  0
 
>>> S Orted ([5, 9, O], reversed_cmp)
[36, 21, 12, 9, 5]

function as the return value

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.
Closed Bag

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
>>> F2 ()
9
>>> f3 ()
9

The reason is that the loop has executed while calling Count, but F () has not been executed until it is invoked. So the return function does not refer to any of the loop variables, or to subsequent variables that change.
anonymous function (lambda expression)

Equivalent to:

def f (x): Return
  x * x

The keyword lambda represents an anonymous function, and the x in front of the colon represents the function argument.
anonymous function as return value

def build (x, y): Return
  lambda:x * x + y * y

Adorners (@func)

The way to dynamically add functionality during code runs, called "adorners" (decorator), in essence, decorator is a higher-order function of the return function.

def log (func):
  def wrapper (*args, **kw):
    print ' call%s (): '% func.__name__ return
    func (*args, **kw)
  Return wrapper
 
@log def today ()
:
  print ' 2013-12-25 '
 
>>> Now ()
:
2013-12-25
 
#相当于执行: Now
 
= log
back to top
with parameter adorner
 
def log (text):
  def Decorator (func):
    def wrapper (*args, **kw):
      print '%s%s (): '% (text, func.__name__) return
      func (*args, **kw)
    Wrapper return
  decorator
 
@log (' Execute ')
def now ():
  print ' 2013-12-25 '
 
#执行结果
> >> now ()
Execute today ():
2013-12-25
 
#相当于执行:
 
>>> now = log ("Execute") (now)

Anatomy: First execute log (' Execute '), return the Decorator function, then call the returned function, the parameter is now function, the return value is the wrapper function finally.

__name__
Because the __name__ of the function has changed, the code that relies on this will make an error. So use 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
 
#对于带参函数
 
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 functools
>>> int2 = functools.partial (int, base=2)
>>> int2 (' 1000000 ')
>>> int2 (' 1010101 ')
 
#相当于:
 
def int2 (x, base=2): return
  int (x , base)
 
max2 = functools.partial (max, 10)

is equivalent to specifying the first argument for the Max function

MAX2 (5, 6, 7)
 
#相当于:
 
Max (10, 5, 6, 7)

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.