可变参数

Python 中级:面向开发者

Jasmin Ludolf

Curriculum Manager

固定参数的局限

def average(values):
    """Find the mean in a sequence of values and round to two decimal places."""

    average_value = sum(values) / len(values)
    rounded_average = round(average_value, 2)
    return rounded_average

# 使用六个参数 print(average(15, 29, 4, 13, 11, 8))
TypeError: average() takes 1 positional argument but 6 were given
Python 中级:面向开发者

可变位置参数

  • 文档字符串有助于说明如何使用自定义函数

  • 可变参数允许函数接受任意数量的参数

# 允许任意数量的位置(非关键字)参数
def average(*args):
    # 函数代码保持不变
  • 约定命名:*args

  • 兼容多种用法,且结果可预期!

Python 中级:面向开发者

使用可变位置参数

# 使用六个位置参数调用 average
print(average(15, 29, 4, 13, 11, 8))
13.33
Python 中级:面向开发者

Args 合并为单个可迭代对象

  • *:将参数转换为单个可迭代对象(元组)
# 跨多列表计算
print(average(*[15, 29], *[4, 13], *[11, 8]))
13.33
Python 中级:面向开发者

可变关键字参数

# 使用可变关键字参数
def average(**kwargs):

average_value = sum(kwargs.values()) / len(kwargs.values()) rounded_average = round(average_value, 2) return rounded_average
  • 可变关键字参数:**kwargs

  • keyword=value

Python 中级:面向开发者

使用可变关键字参数

# 使用六个关键字参数调用 average
print(average(a=15, b=29, c=4, d=13, e=11, f=8))
13.33
# 使用一个关键字参数(字典)调用 average
print(average(**{"a":15, "b":29, "c":4, "d":13, "e":11, "f":8}))
13.33
  • 字典中的每个键值对都会映射为一个关键字参数及其值!
Python 中级:面向开发者

Kwargs 合并为单个可迭代对象

# 使用三个关键字参数组调用 average
print(average(**{"a":15, "b":29}, **{"c":4, "d":13}, **{"e":11, "f":8}))
13.33
Python 中级:面向开发者

Passons à la pratique !

Python 中级:面向开发者

Preparing Video For Download...