04-Python function 2

## Scope function

- Python scope:
  - Built-in scope
  - File scope
  - functions nested scopes
  - local scope
- the inclusion relation: the built-in scope (the file scope (function nested scopes (local scope))).
  - You can use scopes between external variables and functions in scope.
  - The scope of the variable domain can not be used directly on the outside.
- classified according to the size of scope:
  - a global variable (Global): a function of external definition
    - the definition file and scope built scope variables and functions are part of the global variables.
  - local variables (local): defined inside the function
    - locally nested scopes and scope defined variables and functions are all local variables (local variables).
- variable scope is accessible range of variables, also known as a namespace.
  - variable assignment for the first time, Python create variables
  - the first assignment to a variable position determines the scope of the variable.
  - in the same scope, variable names are unique.
  - in a different scope, the same variable name also expressed different variables.
  - variable scope is limited by:
    - the definition of a local scope inside has a function of variables defined outside the function has global scope.
    - Local variables can only be declared inside a function of its access to global variables can be accessed throughout the program range.
    - the function is called, all variables declared within a function name will be added to the local variables.

# Toplevel 
a, b = 5, 0 # a, e is a global variable 
def sum (c, d): # c, d is in the local variable SUM 
    F = 100 # Create a local variable 
    e = c + d + a; # e here is a local variable, a is an outside function of global variables 
    return E 
 
# call the sum function 
S = sum (10, 20 is) 
Print (S)    
Print ( "external function is a global variable:", B) 
# results 
# 35 
external function is a global variable #: 0 
    
"" " 
during the program operation, will produce a, b, c, d, f, e and variables sum 7 names. 
a e and global variables to file scope 
c, d, f, e is a function of the internal variable add 
"" "
# Follow the "local" priority principle, the outer shield scope is 
a = 100 # global variable 
DEF ADDD (B): 
    A = # 0 local variable, global variable shield A 
    C = A + B 
    return C 
Print (ADDD (12 is) ) 
# result 
12

- global statement:

  - Global variables can be used without defined within the function.

  - the local variables global variables inside a function.

DEF Fun1 (): 
    , Ltd. Free Join A   
    A = 100 # A global variable 
    b = 200 
Print (A) # A global variable, it is possible to call 
# print (b) being given, because b is Fun1 internal variables can not call 
# results 
100
A, B = 100, 12 is   
DEF FUNC ():   
    Global A # A is a global variable. 
              # If there is already a global variable that refers to a variable that is global if it did this would Num new definition of a global variable. 
    a = 200 # every function within the variable Num always refer to global variables. In addition there is no local variable is called Num. 
    Print (A)   

FUNC ()   
Print (A) # output 200 illustrates modification is a global variable 

DEF fun1 ():   
    Global b   
    b =. 3 
    Print (b)   
b = 120 # has no effect on the global variable, a new definition of a variable b 
fun1 ()   
Print (B) output # 3 defines a global description of the new variable + B 

# result 
200 is 
200 is 
3 
3

## function nested definitions

- Python allows internal function defined functions.

- Internal-defined function, the function can only be used internally

# Find the square of the hypotenuse 
DEF Fun1 (A, B): 
    DEF Fun2 (X): # Fun2 function is not defined in the Fun1 
        S = X * X 
        return S 
    S1 = Fun2 (A) + Fun2 (B) # call Fun2 
    return S1 

# Fun2 (. 5) being given, not external call, a local variable 
Fun1 (3, 4) # 20 output is

## partial function

- scenarios and understand:
  - the function executes, to bring all the necessary parameters to call.
  - When parameter to a function relatively long time, there are parameters can be informed in advance before the function is called, which in most cases is some fixed value.
  - To simplify the calling function, you can create a new function
    - a function of the parameters used to specify, for a fixed value, this new function is the "partial function."

- Syntax:
  - Mode 1: Create a new function
  - way: by functools call partial function modules
    - Import functools
    - newfunc functools.partial (function, specify a particular parameter = value) =

# A manner 
def Fun1 (a, b, c , d = 2): the value of D has been secured # 
    Print (A + B + D + c)   
    
Fun1 (1, 2,4) outputs # 9 
# For the c in the subsequent value has been fixed all calls in 5 
# or want to change the value of d, where all calls are took to modify the value of 
# calling function Fun1 (1,2, C = 5, d =. 3) 
# if every time this function is called to write the parameters must be repeated = 5 c, d = 3 

# create new functions 
DEF Fun2 (a, b, c = 5, d = 3): 
    Fun1 (a, b, c, d ) 
# direct input a, b values, c, d has been fixed     
Fun2 (1,2) # output. 1 + 2 +. 5 = +. 11. 3 
# is a partial function Fun2
# Second way 
Import functools 
DEF Fun1 (A, B, C, d = 2): d has a fixed value of # 
    Print (A + B + C + d)   
Fun1 (l, 2,3) is output # 8 
# modifications d value 
NewFun = functools.partial (Fun1, D =. 5) 
NewFun (l, 2,3) is output # 11 
# modifications c, d values 
NewFun1 = functools.partial (Fun1, =. 3 C, D =. 5) 
NewFun1 (1,2) output is 11 #

## recursive function

- recursive function refers to the calling function in the body of the function itself.
- recursive function Features:
  - recursive function theory, will always continue to perform, there must be a definite end conditions.
  - usually a large, complex problem into layers of a problem with the original smaller problem to solve similar.
  - the advantage of a simple recursive function is defined, clear logic.

"" " 
DEF Story (): 
    Story () 
    " "" # theory will infinite loop. . . 
# Factorial. 1 * 2 * = n-*. 3 .....! 
DEF Fun1 (n-): 
    IF n-==. 1: 
        return n- 
    elif n->. 1: 
        return Fun1 n-* (n--. 1) 
    the else: 
        return 'Please parameter passing is greater than zero ' 
Print (Fun1 (. 5)) output # 120

## higher-order functions

- Concept: When parameter to a function, but also to accept another function, put this function is called higher-order function

DEF Fun1 (A, B): 
    return A + B 

DEF Fun2 (A, B): 
    return ab & 

DEF fun3 (A, B, fun): # Parameter fun as a function 
    RES = fun (A, B) 
    return RES 

V = fun3 (. 1, 2, Fun1) 
Print (V) output # 3

- within the system some of the higher-order functions:

  - Map ():
    - The mapping functions provided to make the specified sequence.
    - Format: Map (function, Iterable, ...)
      - The argument function of a function call to the function parameters of each element in the sequence, each new list of functions returns a return value of function.
      - The second parameter refers to one or more iterable class objects iterations

l1 = [i for i in range (20) if i% 2 == 0] # generate a sequence 
l2 = [] # define an empty list 
for in L1 I: 
    l2.append (10 * I)     
Print (L2) 

# use map to achieve 
DEF Fun1 (i): 
    return i * 10     
# to call the map function 
L3 = map (Fun1, L1) 
Print (of the type (map)) 
Print (L3)    
for i in L3: 
    Print (i, End = "") 
    
results # 
[0, 20 is, 40, 60, 80, 100, 120, 140, 160., 180 [] 
<class 'type'> 
<Map Object AT 0x000001CD8AFE8CC0> 
0 40 60 20 is 80 100 120 140 160. 180 [

  - the reduce ()
    - is intent merge, cut. Function parameters will be accumulated elements in a sequence, to merge into an iterator object is a result
    - as a function of the parameters are required: must have two parameters, has to return the result
    - the reduce package need to import functools

    - 格式:reduce(function, iterable[, initializer])

      -  function - a function, there are two parameters

      - iterable - iterables

      - initializer - optional, initial parameter

      - (two parameters) of the first set of first and second elements with the function operates in the function passed to reduce, then the resulting data to the third function operation function, to obtain a final result.

from functools import reduce 
create a sequence # 
L1 = [I for I in Range (. 6)] 
# summing function 
DEF myAdd (X, Y): 
    return X + Y 
RST = the reduce (myAdd, L1) # 0 + + +2. 1 +4 +5 = 15. 3 
Print (RST) output # 15

  - filter()

    - filter function: a group of data filtering, qualified data will generate a new list and return
    - the queue order is not necessarily one to one and the opposite map
    - Format: filter (function, Iterable)
      - function: Analyzing functions
      - iterable: iterables

# Judging function 
DEF IsEven (A): 
    return ==. 1 A 2% 
# 2% ==. 1 A is a determination condition 
l = [i for i in range (20)] # create a sequence 
rst = filter (IsEven, l) # call filter 
Print (RST, type (RST)) 
for I in RST: 
    Print (I, End = "") 
    
# results 
<0x000001CD8AFE8AC8 AT filter Object> <class 'filter'> 
. 1. 5. 7. 9. 3 15. 17. 19. 11 13 is  

  - sorted()

    - according to the sorting iterables given algorithm
    - Format: the sorted (Iterable [, CMP [, Key [, Reverse]]])
      - Iterable: iterables.
      - cmp: compare function.
      - key: before sorting element for each function key operation
      - reverse: collation, reverse = True descending, reverse = False ascending (default).

Sorted by size # 
A = [234,343,64,63,74,643] 
Al = the sorted (A, Reverse = True) 
Print (Al) 
# sorted by absolute value of 
a = [-34,43, -456,5353,53] 
the sorted = Al (A, Key = ABS, Reverse = True) 
Print (Al) 
# results 
[643, 343, 234, 74, 64, 63] 
[5353, -456, 53, 43, -34]

## return function

- function returns a specific value, it can function as a return result

# Is returned in the body of the function definition of the function 
DEF MyF2 (): 
    DEF MyF3 (): 
        Print ( "FFF3") 
        return "which is the return content" 
    return MyF3 

## 
F = MyF2 () 
Print (type (F)) # < class' function '> 
Print (F) # <MyF2 function. <about locals> .MyF3 AT 0x00000207E20D3F28> 
F ()   
"" " 
FFF3 
' return the contents of which is" 
"" " 
# call MyF2 () function, it then performs the MyF3 ()

 

  

 

  

 

Guess you like

Origin www.cnblogs.com/cmn-note/p/11197850.html