python_ function notes

Chapter II Functional Programming

Definition: function refers to a collection of statements by a name (function name) encapsulates, in order to perform this function, you can simply call the function name

characteristic:

  1. Reduce duplication of code

  2. So that the program becomes scalability

  3. Making the program easy to maintain

Parameter variables

Only allocate memory cells only when called, at the end of the call, immediately release the memory unit allocated. Thus, the parameter is valid only within the function. Function call returns to the main calling function with the rear end can no longer use the variable parameter

Arguments

May be constants, variables, expressions, functions, etc., whether the argument is an amount of what type of, during function calls, they must have a certain value, in order to transmit these values to the parameters. Therefore should be pre-assigned to the arguments 

DEF COUNT ( X, y):   # X, y represents a parameter 
COUNT (5,8)   # 5,8 parameters represent actual

Positional parameters

Position parameter according to the formal and actual parameters are associated with

key parameter

Location parameter> key parameters / default parameters

Non-fixed parameters

In the back of the key parameters and default parameters do not know how many will pass back the value of args: save as tuples in the form of a dictionary Save as: kwargs

Local variables and global variables

Local variables: the definition of temporary variables inside a function is useful only within the function does not affect the global variable locals way to find all the variables inside the function  to show up in the form of a dictionary globals method looks for a global variable

Global variables: the program defined in the global process of running the global callable      

  • Variables defined in a local variable called the function, the variable a defined at the beginning of the procedure called global variables.

  • Global variable scope (i.e. the effective range) is the entire program, the local variable is a function of the variable scope of the definition.

  • Find order of the variables are local variables> Global Variables

  • When a global variable and a local variable with the same name in the function definition of local variables, local variables play a role; global variables to function elsewhere.

  • In the function is not directly modify global variables

Anonymous function

Anonymous functions that do not need to explicitly specify the function name

# Code 
DEF Calc ( X, Y): return X ** Y Print ( Calc ( 2, . 5)) # anonymous function into Calc = the lambda X, Y: X ** Y Print ( Calc ( 2, . 5) )
   



Generally used with anonymous functions and other functions

res = map(lambda x:x**2,[1,5,7,4,8])
for i in res:
   print(i)

Nested functions

In each function variables declared within the function are independent and do not affect each nested function variable lookup rules is to first look at the current level and gradually turn up to find

Higher-order functions

Variables can point to functions, function parameters can accept variable, a function can accept another function as an argument, this function is called higher-order functions. As long as a function of the following two conditions meet is called higher-order functions:

  1. Receiving one or more of the parameters as a function of

  2.         Further function returns a return

  3. Example:

    def get_obs(n):
       if n < 0:
           n = int(str(n).strip('-'))
       return n
    def abb(x,y,z):
       return z(x) + z(y)
    res = abb(5,-8,get_obs)
    print(res)

     

recursive function

Inside the function can call other functions, then it can call its own, so to call itself a function is recursive functions

  1. There must be a definite end condition

  2. Each time deeper into the recursive, recursive problem size should be reduced compared to last

  3. Recursive efficiency is not high, too much will cause the level of recursion stack overflow (in the computer, the function call is achieved through the stack (Stack) This data structure, each time a function call into the stack the stack frame is increased by one, each when the function returns, the stack will cut a layer stack frame. Since the size of the stack is not infinite, so the number of recursive calls too much will result in a stack overflow)

Recursion in a particular scene is quite useful, after some algorithms have to learn to use recursion, such as heap row, row faster, and now look a little complicated, later revisit.

Common built-in functions

name effect
to you Returned object callable attributes
divmod Returns the quotient and remainder of the division, such divmod (4,2), the result (2, 0)
enumerate Returns the index of the list of elements, such as d = [ "alex", "jack"], the enumerate (d), to give (0, 'alex') (1, 'jack')
eval It can be a string list, dict, set, tuple, which is converted to the original data type. # String known only to the hard disk, the data type is displayed in memory
filter On the list, dict, set, tuple, etc. iterables filter, filter (lambda x: x> 10, [0,1,23,3,4,4,5,6,67,7]) was filtered off all particles larger than value of 10
map map (lambda x: x ** 2, [1,2,3,43,45,5,6,]) output [1, 4, 9, 1849, 2025, 25, 36]
frozenset Put into a set unmodifiable #add added to the set of elements
globals Print the value in the global scope
reversed A list can be reversed
round 4 can be rounded decimal 5 into integers, round (10.15,1) to give 10.2
sum Summing, a = [1, 4, 9, 1849, 2025, 25, 36], sum (a) to give 3949
zip In the two or more makes up a list, a = [1, 4, 9, 1849, 2025, 25, 36], b = [ "a", "b", "c", "d"], # zipper form
center The method of centering a string, the first parameter is the width, the second parameter is one filler
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   

Closure function

闭包的意义:返回的函数对象,不仅仅是一个函数对象,在该函数外还包裹了一层作用域,这使得,该函数无论在何处调用,优先使用自己外层包裹的作用域

名称空间

又名name space, 顾名思义就是存放名字的地方,存什么名字呢?举例说明,若变量x=1,1存放于内存中,那名字x存放在哪里呢?名称空间正是存放名字x与1绑定关系的地方

python里面有很多名字空间,每个地方都有自己的名字空间,互不干扰,不同空间中的两个相同名字的变量之间没有任何联系。

名称空间有4种:LEGB

  • locals:函数内部的名字空间,一般包括函数的局部变量以及形式参数

  • enclosing function:在嵌套函数中外部函数的名字空间, 若fun2嵌套在fun1里,对fun2来说,fun1的名字空间就enclosing.

  • globals:当前的模块空间,模块就是一些py文件。也就是说,globals()类似全局变量。

  • builtins: 内置模块空间,也就是内置变量或者内置函数的名字空间,print(dir(builtins))可查看包含的值。

不同变量的作用域不同就是由这个变量所在的名称空间决定的。

作用域即范围

  • 全局范围:全局存活,全局有效

  • 局部范围:临时存活,局部有效

查看作用域方法 globals(),locals()

''

 

Guess you like

Origin www.cnblogs.com/xiaolang666/p/11967855.html