使用可变长度关键词参数(**kwargs)的函数
让我们在灵活参数上更进一步——您已经用过 *args,现在将使用 **kwargs!**kwargs 的不同之处在于,它允许您向函数传入可变数量的「关键词参数」。回忆上一段视频的内容,在函数定义内部,kwargs 是一个字典。
为了更好地理解这一点,您将在本练习中使用 **kwargs 来定义一个可接收任意数量关键词参数的函数。该函数模拟一个简单的状态报告系统,用于打印电影角色的状态。
本练习是课程的一部分
Python 函数入门
练习说明
- 补全函数头,函数名为
report_status。它只接受一个灵活参数**kwargs。 - 遍历
kwargs的键值对,并打印键和值,二者用冒号 ':' 分隔。 - 第一次调用
report_status()时,传入以下关键词-值对:name="luke"、affiliation="jedi"、status="missing"。 - 第二次调用
report_status()时,传入以下关键词-值对:name="anakin"、affiliation="sith lord"、status="deceased"。
交互式实操练习
通过完成这段示例代码来试试这个练习。
# Define report_status
def ____(____):
"""Print out the status of a movie character."""
print("\nBEGIN: REPORT\n")
# Iterate over the key-value pairs of kwargs
for ____, ____ in kwargs.items():
# Print out the keys and values, separated by a colon ':'
print(____ + ": " + ____)
print("\nEND REPORT")
# First call to report_status()
# Second call to report_status()
report_status(name=____, affiliation=____, status=____)