Python (5) 如何使用*args和**kwargs

2016-12-21  本文已影响0人  麦兜胖胖次

这是一种特殊的语法,在函数定义中使用 *args**kwargs 传递可变长参数。 *args用作传递非命名键值可变长参数列表(位置参数); **kwargs用作传递键值可变长参数列表。

在python中,支持可变参数,其中参数分为不带键值,由位置决定的,由*args来指定。还有一种参数带键值,需要有key来指定,可以有default,由**kwargs来指定。

下面一个例子使用*args,同时包含一个必须的参数:

def test_args(first, *args): 
  print 'Required argument: ', first 
  for v in args: print 'Optional argument: ',v

test_args(1, 2, 3, 4)

# result:
# Required argument: 1
# Optional argument: 2
# Optional argument: 3
# Optional argument: 4

下面一个例子使用**kwargs, 同时包含一个必须的参数和*args列表:

def test_kwargs(first, *args, **kwargs): 
  print 'Required argument: ', first 
  for v in args: 
    print 'Optional argument (*args): ', v 
  for k, v in kwargs.items(): 
    print 'Optional argument %s (*kwargs): %s' % (k, v)

test_kwargs(1, 2, 3, 4, k1=5, k2=6)

# results:
# Required argument: 1
# Optional argument (*args): 2
# Optional argument (*args): 3
# Optional argument (*args): 4
# Optional argument k2 (*kwargs): 6
# Optional argument k1 (*kwargs): 5

关于pop函数的使用函数:
The pop method of dicts (like self.data
, i.e. {'a':'aaa','b':'bbb','c':'ccc'}, here) takes two arguments.
http://docs.python.org/library/stdtypes.html?highlight=dict.pop#dict.pop

The second argument, default, is what pop
returns if the first argument, key, is absent. (If you call pop with just one argument, key
, it raises an exception if that key's absent).
之前一直都不知道pop原来还有第二个参数...直到看到了kwargs.pop(key, default)才明白。

参考:
http://kodango.com/variable-arguments-in-python
https://docs.python.org/3/library/stdtypes.html#dict.pop

上一篇下一篇

猜你喜欢

热点阅读