# coding = Utf-8 ' function declaration: def name ([arg,... arg = value,... *arg, **kwarg]): Suite1. When the compiler encounters a def, the Create function object directive is generated. In other words, DEF is a command line, not just a grammar keyword. The function object can be created dynamically on any ground side. 2. You can use the default, variable, and keyword parameters arg = value is the default parameter *args is a mutable parameter, and args receives a tuple; **kwargs is the keyword argument, Kwargs receives a dict. The lambda function differs from the definition of a complex function with Def, a lambda can only be a simple expression with a return value. To use an assignment statement to throw a syntax error, consider using a function instead. "'" *****************************************************1. function creation functions are the first class of objects that can be used as arguments or return values for other functions. The function always has a return value. Even if there is no return, the default will return none. "Def test1 (name):" ' >>> test1 (' a '). __name__ # View function Returns the name of the function ' a ' >>> test1 (' B '). __name__ # View function return function name ' B ' >>> test1 (' a ') # function returned by the calling function Call function a >>> print (test1 (' C ')) # calls the functions and returns 2 values: Integer and string (0, ' test ') ' if name = = ' A ': D EF A (): print (' Call function a ') return a elif name = "B": Def b (): Pass return b E Lse:return 0, ' test"' *************************************************************2. Parameter 2.1 function is flexible and changeable, can be transmitted according to the order of the position, also can not close the order? Name the argument. ' Def test21 (A, B): ' >>> test21 # position Parameters 1 2 >>> test21 (b=3,a=4) # named parameter 4 3 "Print (A, b)" "************************************* 2.2. The default value of the hold parameter. However, to??, the default value object is generated when the function is created, all calls are made to the. Object. If the default value is a mutable type, it is like a C static local variable. "Def test22 (x, lst=[]):" ' >>> test22 (1) [1] >>> test22 (2) # keep the last tune state. [1, 2] >>> test22 (3, []) # explicitly provide an argument, do not use the default value. [3] >>> test22 (3) # make again? With default values, the default list object will continue to be used [1, 2, 3] "lst.append (x) return LST" ************* 2.3 The default parameter? You cannot have other positional parameters unless you are a variable. Syntaxerror:def test23 (A, b=1, c): Pass 2.4 uses *args to collect "extra" positional parameters, **kwargs collect "additional" named parameters.These two names are just conventions, but freely named. *args is a mutable parameter, and args receives a tuple; **kwargs is the keyword parameter, Kwargs receives a dict. "Def Test24 (A, b=1, *args, **kwargs): ' >>> ; Test24 (0) 0 1 () {} >>> Test24 (0,2,3,4) 0 2 (3, 4) {} >>> Test24 (0,2,3,4,x =5) 0 2 (3, 4) {' X ': 5} # you can "expand" the sequence type and the dictionary to use all the elements as multiple arguments. If it does not unfold, it is only a single argument object. >>> Test24 (*range (5), **{' x ': ten, ' Y ': one}) 0 1 (2, 3, 4) {' X ': ten, ' Y ': one} >>> Test24 (r Ange (5)) range (0, 5) 1 () {} # single "*" Expands the sequence type, or only the dictionary's primary key list. # "* *" expands dictionary key-value pairs. However, if no parameters are collected, the extra arguments after the expansion will throw an exception. >>> p = dict (a=20,b=21) >>> Test24 (p) {' A ': +, ' B ': +} 1 () {} >>> test24 (* P) # expands only keys (), Test ("A", "B") a B () {} >>> Test24 (**p) # expands items (), test (a = 1, b = 2). () {} ' Print (a) print (b) print (args) print (kwargs) * * *3. Scope 3.1 function parameters and internal variables are stored in the locals namespace. "Def test31 (A, b=1):" ' >>> test31 (100) {' s ': ' Hello Python ', ' B ': 1, ' a ': 100} "s = ' Hello Python ' print (Locals ()) '" ************************************************************* 3.2 except for the use of G Lobal, nonlocal specifically, otherwise, use an assignment statement inside a function, always creating a new object association in the locals namespace. Note: "Assignment" refers to a name pointing to a new object,?? Change the state of an object by its name. Name Lookup order: Locals, enclosing function, globals, __builtins__? Locals: function internal namespace, including local variables and formal parameters. Enclosing function: namespace for outer nested functions.? Globals: The namespace of the module in which the function is defined. __builtins__: Namespaces for built-in modules. If you do not modify global variables, you can also not use the Global keyword. Python3 provides the nonlocal keyword to modify the outer nested function namespace, python2.7 not. The nonlocal keyword is used to use an outer (non-global) variable in a function or other scope. ' x, y = 1, 2 # Global variables directly defined at the module level def test321 (): Globals X # Reference global variable x = one y = 21 # Here's y is local changeVolume Global Z # defines a global variable within the function, without defining z = 3 Print at the module level (' In test321 (): x=%d; y=%d; z=%d '% (x, y, z)) def test322 (): Print (' in test322 (): x=%d; y=%d; z=%d '% (x, y, z) # Direct access to all global variables, including variable z# test print (' Out 1:x=%d; y=%d; Z=undefine '% (x, y)) test321 () test322 () print (' Out 2:x=%d; y=%d; z=%d '% (x, y, z)) ' *************************** 3.3 Closure Closure (closure) is an important grammatical structure of functional programming. Closures are also a structure for organizing code, which also improves the reusable nature of code. "Def Lineconfig (A, B):" In this example, the function line and the environment variable A, a and B constitute the closure. When we created the closure, we explained the values of the two environment variables through the line_conf parameter, a and B, so that we determined the final form of the function (y = x + 1 and y = 4x + 5). We only need to change the parameter, a, B, we can get a different line expression function. Thus, we can see that closures also have the effect of improving code reusability. >>> y1 = lineconfig (1, 1) # defines the line y = x + 1 >>> p1 = y1 (2) # Calculates the y-coordinate, gets x=2 when Y1 value >&G t;> print (p1) 3 >>> lstpoint = [Y1 (x) for x in range (3)] # Calculate y-coordinate list >>> print (lstpoint) [1 , 2, 3];>> y2 = lineconfig (4, 5) # defines the line y = 4x + 5 >>> p2 = y2 (x=2) # Calculates the y-coordinate, gets x=2 when Y2 value >> > Print (p2) "Def Line (x): return a*x + B return linedef Newcounter (i=0): ' Two independent counters >>> C1 = newcounter () >>> C2 = Newcounter (2) >>> print (C1 (), C1 (), C1 ()) 1 2 3 >& gt;> print (C2 (), C2 (), C2 ()) 3 4 5 "Def counter (): nonlocal I i = i + 1 return i Retu RN Counterif __name__ = = ' __main__ ': Import doctest doctest.testmod (verbose=true)
Using the Doctest Unit test Method Training Tutorial: Python function basics