解释Python中的仅关键字参数(可变参数)
请看下面的代码:
#!/usr/bin/python
# Filename: total.py
def total(initial=5, *numbers, **keywords):
count = initial
for number in numbers:
count += number
for key in keywords:
count += keywords[key]
return count
print(total(10, 1, 2, 3, vegetables=50, fruits=100))
有人能解释一下 *numbers 和 **keywords 是怎么获取参数的吗?简单的解释会非常感谢!提前谢谢你!
2 个回答
我们先来拆解一下这个函数。
这个总和函数有三个参数。
- initial=5 => 这是一个关键字参数。
- *numbers => 这个也叫做 *args。你可以传入任意数量的参数。
- **keywords => 这是一个像字典一样的关键字参数,每个键都和一个特定的值相关联。
==========================================
count = initial
*我们知道 initial 是一个关键字参数,它的值是 5。所以现在 5 的值被赋给了一个叫 count 的变量。
for number in numbers:
*这里的 number 是一个占位符变量,用来表示 numbers。
*我们知道 numbers 是一个任意参数,所以它可以接受任意数量的参数或值。
*所以现在 number 将包含在执行函数时传入的 numbers 参数中的值。
count += number
*每次循环通过 numbers 参数时,它都会把 count 加上当前的 number,并返回一个新的 count 值。
*当 count 是 5 时,它会循环处理参数,并把第一个参数加到 count 上。这会一直重复,直到循环结束。
for key in keywords:
*这部分有点复杂,因为这个参数是字典类型,里面包含了键和对应的值。
count += keywords[key]
return count
100 + 50 + (10, 1, 2, 3) => 166。
我知道这个回答有点长,但理解每个函数背后的基本概念是一个全面的程序员的重要能力。
在你的代码中,numbers
被赋值为一个包含 (1,2,3) 的元组。keywords
被赋值为一个字典,这个字典里有 vegetables
和 fruits
。
一个星号(*
)表示位置参数。这意味着你可以接收任意数量的参数。你可以把传入的参数当作一个元组来处理。
两个星号(**
)表示关键字参数。
参考资料可以在 这里找到。
示例
Python 2.x(在关键字参数仅限之前)
def foo(x, y, foo=None, *args): print [x, y, foo, args]
foo(1, 2, 3, 4) --> [1, 2, 3, (4, )] # foo == 4
foo(1, 2, 3, 4, foo=True) --> TypeError
Python 3.x(带有关键字参数仅限)
def foo(x, y, *args, foo=None): print([x, y, foo, args])
foo(1, 2, 3, 4) --> [1, 2, None, (3, 4)] # foo is None
foo(1, 2, 3, 4, foo=True) --> [1, 2, True, (3, 4)]
def combo(x=None, *args, y=None): ... # 2.x and 3.x styles in one function
虽然经验丰富的程序员能理解在 2.x 中发生了什么,但这其实有点反直觉(只要有足够的位置参数,一个位置参数就会被绑定到 foo=
,而不管关键字参数)
Python 3.x 引入了更直观的关键字参数仅限的概念,详细信息可以查看 PEP-3102(在可变参数之后的关键字参数只能通过名称绑定)