Fork me on GitHub

Python函数的带星号*参数

1. 三种类型的函数参数

def func(arg, *args, **kwargs):
    print (arg, type(arg))
    print (args, type(args))
    print (kwargs, type(kwargs))

#arg     --  固定参数,必填
#args    --  位置参数,可选
#kwargs  --  关键字参数,可选

如果同时出现(两两,或全部),三种类型的参数必须按序排列:

(arg, *args, **kwargs)

否则函数定义或者函数调用的时候都会出错。

2. 固定参数arg

>>> def func(arg):
...     print arg
... 
>>> func()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: func() takes exactly 1 argument (0 given)
>>> func(1)
1

3. 位置参数args

1) 函数定义 -- tuple打包

>>> def func1(*args):
...     print (args, type(args))
... 
>>> func1()
((), <type 'tuple'>)
>>> func1(1)
((1,), <type 'tuple'>)
>>> func1(1,2,3)
((1, 2, 3), <type 'tuple'>)

2) 函数调用 -- tuple解包

>>> def func2(arg):
...     func1(*arg)
... 
>>> func2()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: func2() takes exactly 1 argument (0 given)
>>> func2(1)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 2, in func2
TypeError: func1() argument after * must be a sequence, not int
>>> func2((1,))
((1,), <type 'tuple'>)
>>> func2((1,2,3)) ((1, 2, 3), <type 'tuple'>)

4. 关键字参数kwargs

1) 函数定义 -- dict打包

>>> def func1(**kwargs):
...     print (kwargs, type(kwargs))
... 
>>> func1()
({}, <type 'dict'>)
>>> func1(1)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: func1() takes exactly 0 arguments (1 given)
>>> func1(a=1)
({'a': 1}, <type 'dict'>)
>>> func1(a=1,b=2,c=3)
({'a': 1, 'c': 3, 'b': 2}, <type 'dict'>)

2) 函数调用 -- dict解包

>>> def func2(arg):
...     func1(**arg)
... 
>>> func2()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: func2() takes exactly 1 argument (0 given)
>>> func2(1)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 2, in func2
TypeError: func1() argument after ** must be a mapping, not int
>>> func2(a=1)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: func2() got an unexpected keyword argument 'a'
>>> func2({'a': 1})
({'a': 1}, <type 'dict'>)
>>> func2({'a': 1, 'b': 2, 'c': 3})
({'a': 1, 'c': 3, 'b': 2}, <type 'dict'>)

 

posted on 2013-06-15 10:59  RussellLuo  阅读(1311)  评论(0编辑  收藏  举报

导航