5200.8.7 任意参数,包括 Arbitrary Number of Arguments 和 Arbitrary Keyword Arguments

Passing an Arbitrary Number of Arguments

(Sometimes you won’t know ahead of…) 有时候你不能提前知道一个函数需要多少参数,python 支持从调用函数中收集任意数量的参数。

def make_pizza(*toppings):
    """Print the list of toppings that have been requested."""
    print(toppings)
make_pizza('pepperoni')
make_pizza('mushrooms', 'green peppers', 'extra cheese')

星号(asterisk) 在参数名字里,*toppings 代表一个 5200.2.4 Tuple,被称作 toppings,包含所有这个函数接受的数据。

def make_pizza(*toppings):
    """Summarize the pizza we are about to make."""
    print("\nMaking a pizza with the following toppings:")
    for topping in toppings:
        print(f"- {topping}")
 
make_pizza('pepperoni')
make_pizza('mushrooms', 'green peppers', 'extra cheese')

Using Arbitrary Keyword Arguments

(Sometimes you’ll…) 如果你不知道要传入什么数据的参数,你的函数可以接受调用语句提供的任意数量的键值对。

参数前的双星号**user_info使Python创建一个名为user_info的Dictionart,其中包含函数接收到的所有额外键值对。

def build_profile(first, last, **user_info):
    """Build a dictionary containing everything we know about a user."""
    user_info['first_name'] = first
    user_info['last_name'] = last
    return user_info
 
user_profile = build_profile('albert', 'einstein',
                             location='princeton',
                             field='physics')
print(user_profile)