Section 110.1: 编写函数时使用 **kwargs
您可以在参数名称前使用双星符号 ** 来定义一个可以接受任意数量关键字(命名)参数的函数:
def print_kwargs(**kwargs):
print(kwargs)
调用方法时,Python 将构造一个包含所有关键字参数的字典,并将其放在函数体中:
print_kwargs(a="two", b=3)
# prints: "{a: "two", b=3}"
需要注意的是,函数定义中的 **kwargs 参数必须始终是最后一个参数,而且只能与前一个参数之后传入的参数相匹配。
def example(a, **kw):
print(kw)
example(a=2, b=3, c=4) # => {'b': 3, 'c': 4}
在函数体内部,kwargs 的处理方式与字典相同;要访问 kwargs 中的单个元素,只需像处理普通字典一样循环查看即可:
def print_kwargs(**kwargs):
for key in kwargs:
print("key = {0}, value = {1}".format(key, kwargs[key]))
现在,调用 print_kwargs(a="2",b=1),输出结果如下:
print_kwargs(a = "two", b = 1)
key = a, value = "two"
key = b, value = 1

Section 110.2: 编写函数时使用 *args
在编写函数时,您可以使用星形 * 在元组中收集所有位置参数(即未命名参数):
def print_args(farg, *args):
print("formal arg: %s" % farg)
for arg in args:
print("another positional arg: %s" % arg)
调用方法:
print_args(1, "two", 3)

在该调用中,farg 将被一如既往地赋值,而其他两个参数将按照收到的顺序被送入 args 元组。
Section 110.3: Populating kwarg values with a dictionary
def foobar(foo=None, bar=None):
return "{}{}".format(foo, bar)
values = {"foo": "foo", "bar": "bar"}
foobar(**values) # "foobar"

Section 110.4: 仅使用关键字和需要使用关键字的参数
Python 3 允许定义只能通过关键字分配的函数参数,即使没有缺省值。这是通过使用星形 * 来消耗额外的位置参数,而不设置关键字参数。* 后面的所有参数都是仅关键字参数(即非位置参数)。需要注意的是,如果只包含关键字的参数没有缺省值,那么在调用函数时仍然需要这些参数。
def print_args(arg1, *args, keyword_required, keyword_only=True):
print("first positional arg: {}".format(arg1))
for arg in args:
print("another positional arg: {}".format(arg))
print("keyword_required value: {}".format(keyword_required))
print("keyword_only value: {}".format(keyword_only))
print_args(1, 2, 3, 4) # TypeError: print_args() missing 1 required keyword-only argument: 'keyword_required'
print_args(1, 2, 3, keyword_required=4)
# first positional arg: 1
# another positional arg: 2
# another positional arg: 3
# keyword_required value: 4
# keyword_only value: True

Section 110.5: 调用函数时使用 **kwargs
您可以使用字典为函数参数赋值;将参数名称作为字典中的键,并将这些参数的值绑定到每个键上:
def test_func(arg1, arg2, arg3): # Usual function with three arguments
print("arg1: %s" % arg1)
print("arg2: %s" % arg2)
print("arg3: %s" % arg3)
# Note that dictionaries are unordered, so we can switch arg2 and arg3. Only the names matter.
kwargs = {"arg3": 3, "arg2": "two"}
# Bind the first argument (ie. arg1) to 1, and use the kwargs dictionary to bind the others
test_func(1, **kwargs)

Section 110.6: **kwargs 和默认值
在**kwargs中使用默认值
def fun(**kwargs):
print(kwargs.get('value', 0))
fun()
# print 0
fun(value=1)
# print 1

Section 110.7: 调用函数时使用 *args
在调用函数时,对参数使用 * 操作符的效果是解包列表或元组参数
def print_args(arg1, arg2):
print(str(arg1) + str(arg2))
a = [1,2]
b = tuple([3,4])
print_args(*a)
# 12
print_args(*b)
# 34
请注意,星号参数的长度必须等于函数参数的个数。
一个常见的 python 习惯做法是在 zip 函数中使用解包操作符 * 来反转其效果:
a = [1,3,5,7,9]
b = [2,4,6,8,10]
zipped = zip(a,b)
# [(1,2), (3,4), (5,6), (7,8), (9,10)]
zip(*zipped)
# (1,3,5,7,9), (2,4,6,8,10)
