根据inspect模块官文文档中关于函数参数类型的相关说明,python函数参数共有五种类型,按顺序分别为:POSITIONAL_ONLY.POSITIONAL_OR_KEYWORD.VAR_POSITIONAL.KEYWORD_ONLY.VAR_KEYWORD.如图: POSITIONAL_ONLY:参数值必须以位置参数的形式传递.python没有明确的语法来定义POSITIONAL_ONLY类型的参数,但很多内建或扩展模块的函数中常常会接收这种参数类型,实际使用中不多见,这里暂不考虑. PO
add by zhj: 在Python文档中清楚的说明了默认参数是怎么工作的,如下 "Default parameter values are evaluated when the function definition is executed. This means that the expression is evaluated once, when the function is defined, and that the same “pre-computed” value is used
函数参数:必选参数.默认参数.可选参数.关键字参数 1.默认参数 默认参数可以简化函数的调用.设置默认参数时,有几点要注意: 一是必选参数在前,默认参数在后,否则Python的解释器会报错: 二是如何设置默认参数.当函数有多个参数时,把变化大的参数放前面,变化小的参数放后面.变化小的参数就可以作为默认参数.使用默认参数最大的好处是能降低调用函数的难度. def power(x, n=2): s = 1 while n > 0: n = n - 1 s = s * x return s2.可选参数
1.位置参数 函数调用时,参数赋值按照位置顺序依次赋值. e.g. def function(x): 3 return x * x 5 print function(2) 输出结果: 4 def function(x, n): return x / n 5 print function(4, 2) 输出结果: 2 2.默认参数 在函数定义时,直接指定参数的值. e.g. def function(x, n = 2): s = 1 while n > 0: n = n -1 s = s * x r