Python中*args和**kwargs的使用

函数定义

使用*args和**kwargs传递可变长参数:

*args用作 传递非命名键值 可变长参数列表(比如元组)

**kwargs用作 传递键值 可变长参数列表(比如字典)

 

函数入参

*args

传递一个位置参数以及两个可变长参数:

1 def test_var_args(farg, *args):
2     print "formal arg:", farg
3     for arg in args:
4         print "another arg:", arg
5 
6 test_var_args(1, "xiaobei", 28)

结果:

1 formal arg: 1
2 another arg: xiaobei
3 another arg: 28

**kwargs

传递一个位置参数和两个键值参数:

1 def test_var_kwargs(farg, **kwargs):
2     print "formal arg:", farg
3     for key in kwargs:
4         print "another keyword arg: %s: %s" % (key, kwargs[key])
5 
6 test_var_kwargs(farg=1, myarg2="xiaobei", myarg3=3)

结果:

1 formal arg: 1
2 another keyword arg: myarg2: xiaobei
3 another keyword arg: myarg3: 3

 

函数调用

在调用函数时,使用*args和**kwargs

*args

1 def test_var_args_call(arg1, arg2, arg3):
2     print "arg1:", arg1
3     print "arg2:", arg2
4     print "arg3:", arg3
5 
6 args = ("hanxiaobei", 28)
7 test_var_args_call(1, *args)

结果:

1 arg1: 1
2 arg2: hanxiaobei
3 arg3: 28

**kwargs

1 def test_var_args_call(arg1, arg2, arg3):
2     print "arg1:", arg1
3     print "arg2:", arg2
4     print "arg3:", arg3
5 
6 kwargs = {"arg3": 35, "arg2": "xiaobei"}
7 test_var_args_call(1, **kwargs)

结果:

1 arg1: 1
2 arg2: xiaobei
3 arg3: 35

 

例子:可接收一个或多个数并计算乘积的函数

1 def product(*args):
2     sum =1
3     for i in args:
4         sum = sum*i
5     print(sum )
6 product(2,6,3,4,5,6,3,1,2,34,43,57)

 

posted @ 2018-01-09 10:21  韩凯1202  阅读(2000)  评论(0编辑  收藏  举报