Here, let's explain some concepts.
-position parameter: The parameter is set by location, and the corresponding parameters are saved implicitly by the tuple. Most of the times we use are by location. For example, there is the function def func (a,b,c), called Func. a=1,b=2,c=3
-Keyword parameters: You can set parameters by keyword, do not care about the parameter position, implicitly save the formal parameter with a dictionary. For example, there is the function def func (a,b,c), called Func (B=1,c=2,a=3), which is a=3,b=1,c=2
Normal format
def func(opt_args): ... return value
function with collect positional parameters
def func(*params): ... return value
def func(*params): print paramsa = [1,2,3,4‘hello‘3func(a, b, c)
Output
([1, 2, 3, 4], ' Hello ', 3)
function with collect keyword parameters
def func(**params): ... return value
def func(**params): print paramsfunc(a=1, b=2, c=3)
Output
{' A ': 1, ' C ': 3, ' B ': 2}
function Special Usage default parameters
- Format
def func (a = 1, b = 2)
The equals sign (=) number is the default value, and you can call a function without having to pass parameters to the default arguments.
def func(a = 1, b = 2): print a, b func(a=3)
Output
3 2
function can return multiple values
Format
Return a, B, c
Instance
def func(a = 1, b = 2): return a, bprint func(a=3)
Output
(3, 2)
inline functions and closures
def foo() #外部函数 def bar() #内嵌函数 .... ....
If an inline function references a variable of an external function (including an external function parameter), the referenced variable is called a free variable, then the inline function is said to be a closure. Let's take a look at the professional explanation: Closure (Closure) is the abbreviation of lexical closure (Lexical Closure), is a function that refers to a free variable. This quoted free variable will exist with this function, even if it has left the environment in which it was created.
def foo(a, b): 4 def bar(): return x * a + b; return barf1= foo(12)f2= foo(23)print f1(), f2()
Output
6 11
Transfer function
Python all objects, functions this syntax structure is also an object, you can pass the function name as a parameter
Format
def bar(*param1, **param2): ....def foo(bar, *param1, **param2): bar(*param1, **param2)
def bar(*param1, **param2): print param1 print param2def foo(bar, *param1, **param2): bar(*param1, **param2)foo(bar, 123, 111222333)
Output
(1, 2, 3)
{' A ': 111, ' C ': 333, ' B ': 222}
anonymous functions and lambda
Lambda syntax can create an anonymous function, the main function is to simplify writing, is a syntactic sugar.
-Format
Lambda [arg1[, arg2, ... ArgN]: expression
def foo(x, y): return x + yprint "call foo function, result is: ", foo(34lambda23 : x + yprint "call lambda fucntion, result is:", bar(3,4)
Output
Call foo function, result is:7
Call Lambda fucntion, result is:7
Introduction to Python functions