python函数参数

来源:互联网 发布:知乎和知乎日报的区别 编辑:程序博客网 时间:2024/06/07 06:34

Python有四种函数参数:

  • Required arguments
  • Keyword arguments
  • Default arguments
  • Variable-length arguments

第1,2,4种参数都是相对于调用来说的,第3种参数是相对于函数定义来说的。

Required arguments

Required arguments are the arguments passed to a function in correct positional order. Here, the number of arguments in the function call should match exactly with the function definition.

即调用函数时,函数参数的数量和位置必须完全匹配函数的定义情况。

Keyword arguments

When you use keyword arguments in a function call, the caller identifies the arguments by the parameter name.
This allows you to skip arguments or place them out of order because the Python interpreter is able to use the keywords provided to match the values with parameters.

e.g.

def func(str):    print strfunc(str=u'haha') 

Default arguments

A default argument is an argument that assumes a default value if a value is not provided in the function call for that argument.

Variable-length arguments

You may need to process a function for more arguments than you specified while defining the function. These arguments are called variable-length arguments and are not named in the function definition.

e.g.

def generic(*args, **kwargs):    print args    print kwargsgeneric('1', 1, nima=1, nida=2)

(‘1’, 1)
{‘nima’: 1, ‘nida’: 2}

可见,required arguments的变长参数被带有一个*的变量接收(形成一个tuple),keywords arguments的变长参数被带有两个*的变量接收(形成一个dict)。





Ref:
http://www.tutorialspoint.com/python/python_functions.htm

0 0