python学习笔记12(函数三): 参数类型、递归、lambda函数

时间:2021-03-02 06:15:25

一、函数参数的类型

  之前我们接触到的那种函数参数定义和传递方式叫做位置参数,即参数是通过位置进行匹配的,从左到右,依次进行匹配,这个对参数的位置和个数都有严格的要求。而在Python中还有一种是通过参数名字来匹配的,这样一来,不需要严格按照参数定义时的位置来传递参数,这种参数叫做关键字参数

>>> def display(a,b):
  print a
  print b

>>> display('hello','world') # 位置参数,即参数是通过位置进行匹配
hello
world
>>> display('hello') # 这样会报错 Traceback (most recent call last):
File "<pyshell#30>", line 1, in <module>
display('hello')
TypeError: display() takes exactly 2 arguments (1 given)
>>> display('world','hello')
world
hello
>>>
>>> display(a='hello',b='world') # 关键字参数
hello
world
>>> display(b='world',a='hello')
hello
world # 可以看到通过指定参数名字传递参数的时候,参数位置对结果是没有影响的。

关键字参数最厉害的地方在于它能够给函数参数提供默认值

>>> def display(a='hello',b='wolrd'):   # 分别给a和b指定了默认参数
print a+b

>>> display()
hellowolrd
>>> display(b='world') # 如果不给a或者b传递参数时,它们就分别采用默认值
helloworld
>>> display(a='hello')
hellowolrd
>>> display('world') # 没有指定'world'是传递给a还是b,则默认从左向右匹配,即传递给a
worldwolrd

注意:在重复调用函数时默认形参会继承之前一次调用结束之后该形参的值

>>> def insert(a,L=[]):
L.append(a)
print L

>>> insert('hello')
['hello']
>>> insert('world')
['hello', 'world'] # 重复调用函数时默认形参会继承之前一次调用结束之后该形参的值

二、任意个数参数(包裹传递

在无法确定参数的个数,就可以使用收集参数了,使用收集参数只需在参数前面加上'*'或者'**'。

'*'和'**'表示能够接受0到任意多个参数,'*'表示将没有匹配的值都放在同一个元组中,'**'表示将没有匹配的值都放在一个字典中。

>>> def func(*name):         # * 表示将没有匹配的值放在同一个元组中
print type(name)
print name >>> func(1,4,6)
<type 'tuple'>
(1, 4, 6)
>>> func(5,6,7,1,2,3)
<type 'tuple'>
(5, 6, 7, 1, 2, 3) >>> def func(**dict): # ** 表示将没有匹配的值放在同一个字典中
print type(dict)
print dict >>> func(a=1,b=2)
<type 'dict'>
{'a': 1, 'b': 2}
>>> func(m=4,n=5,c=6)
<type 'dict'>
{'c': 6, 'm': 4, 'n': 5}

三、递归

如果函数包含了对其自身的调用,该函数就是递归的。

1 def factorial(n):    # 阶乖函数
2 if n==0:
3 return 1 # 0的阶乖返回1
4 else:
5 return n*factorial(n-1) # n的阶乖则返回 n*f(n-1)
6
7 print factorial(10)

四、lambda函数

lambda函数也叫匿名函数,即,函数没有具体的名称。

lambda语句中,冒号前是参数,可以有多个,用逗号隔开,也可以没有,冒号右边的返回值,lambda语句构建的其实是一个函数对象。

>>> g = lambda x : x * 2     # :左边表示参数,右边表示返回值
>>> print g(2)
4

lambda 函数好处:

1、在不需要再复用的地方用lambda,免去函数名,省去函数定义的过程

2、代码更精简