python函数之传参

函数是组织好的,可重复使用的,用来实现单一,或相关联功能的代码段。

函数具有,可重复性,易维护性,提高开发效率等等。

>>> 
>>> def fun1(a,b):
    print(a+b)
>>> fun1(1,2)
3
>>> 

  以上代码是一个简单的函数定义与使用案例。

 ①:位置参数

>>> def fun(a,b,c):
    print(a)
    print(b)
    print(c)
>>> fun(1,2,3)
1
2
3
>>> fun(1,2)
Traceback (most recent call last):
  File "<pyshell#97>", line 1, in <module>
    fun(1,2)
TypeError: fun() missing 1 required positional argument: 'c'
>>> fun(1,2,3,4)
Traceback (most recent call last):
  File "<pyshell#98>", line 1, in <module>
    fun(1,2,3,4)
TypeError: fun() takes 3 positional arguments but 4 were given
>>> 

  由上代码可知位置参数必须一一对应,不能少传参或多传参。

②:关键字传参

>>> def fun(a,b,c):
    print(a)
    print(b)
    print(c)
>>> fun(a=1,c=3,b=2)
1
2
3
>>> fun(a=1,c=3)
Traceback (most recent call last):
  File "<pyshell#111>", line 1, in <module>
    fun(a=1,c=3)
TypeError: fun() missing 1 required positional argument: 'b'
>>> fun(a=1,c=3,b=2,d=4)
Traceback (most recent call last):
  File "<pyshell#112>", line 1, in <module>
    fun(a=1,c=3,b=2,d=4)
TypeError: fun() got an unexpected keyword argument 'd'
>>> 

  由上代码可知,关键字传参无须一一对应,但任然不可少传参及多传参。

③:混合传参

>>> def fun(a,b,c):
    print(a)
    print(b)
    print(c)
>>> fun(1,2,c=3)
1
2
3
>>> fun(a=1,2,3)
SyntaxError: positional argument follows keyword argument
>>> fun(1,b=2,3)
SyntaxError: positional argument follows keyword argument
>>> fun(1,3,b=2)
Traceback (most recent call last):
  File "<pyshell#121>", line 1, in <module>
    fun(1,3,b=2)
TypeError: fun() got multiple values for argument 'b'

  由上代码可知混合传参,关键字参数只能位于左边,且要求一一对应,不可少传参及多传参。

④:默认传参

>>> def fun(a,b=2):
    print(a+b)
>>> fun(1)
3
>>> fun(1,3)
4
>>> 

  由上代码可知,当不给b形参传值时,会使用默认值2,否则使用传递的参数。

⑤:参数组 *args,**kwargs

  *args使用举例

>>> def fun(a,*args):
    print(a)
    print(args)
>>> fun(1)
1
()
>>> fun(1,2,3,4,5,6,7,8)
1
(2, 3, 4, 5, 6, 7, 8)
>>> fun(1,(2,3,4,5,6,7,8))
1
((2, 3, 4, 5, 6, 7, 8),)
>>> fun(1,*(2,3,4,5,6,7,8))
1
(2, 3, 4, 5, 6, 7, 8)
>>> 

由上代码可知,当不给*args传参时,args默认为空元组,第一个参数传值给第一个形参之后,后面的数据以逗号为分割为args的元组数据,在序列前加*则迭代成为args的元素元组。

**kwargs使用举例

>>> def fun(a,**kwargs):
    print(a)
    print(kwargs)
>>> fun(1,b=2,c=3)
1
{'b': 2, 'c': 3}
>>> fun(1,2,3,d=4)
Traceback (most recent call last):
  File "<pyshell#151>", line 1, in <module>
    fun(1,2,3,d=4)
TypeError: fun() takes 1 positional argument but 3 were given
>>> fun(1,1,2,2,2,2,2,y=2,z=3)
Traceback (most recent call last):
  File "<pyshell#152>", line 1, in <module>
    fun(1,1,2,2,2,2,2,y=2,z=3)
TypeError: fun() takes 1 positional argument but 7 were given
>>> fun(1,b=2,c=3,d=4,c=2)
SyntaxError: keyword argument repeated

  由上代码可知,给**kwargs传值时,必须使用赋值模式。

posted @ 2018-12-18 14:25  louis-sun  阅读(1181)  评论(0)    收藏  举报