传递任意数量的实参

一 丶

有时候,你预先不知道函数需要接受几个实参 , 好在python 允许从调用语句中收集任意数量的实参,

例如 , 来看一个制作披萨的函数 , 他需要接受很多配料 , 但你无法预先确定顾客预先要多少种配料 , 下面的函数只有一个

形参*toppings

# 传递任意数量的实参 python
def make_pizza(*toppings):
    """   打印顾客点的所有配料"""
    print(toppings)
make_pizza('Pepperoni')
make_pizza('mushrooms','green peppers','extra cheese')

形参名 *toppings 中的星号让python 创建一个名为toppings的空元祖 , 并将收到的所有值都封装在这的元组里 .ps(python将实参封装到一个元组中,即便函数值只收到了一个值) . 

1.1 结合使用位置实参和任意数量实参

如果要让函数接受不同类型的实参 , 必须在函数定义中将接纳任意数量的实参的形参放在最后,python先匹配位置实参和关键字实参,再将余下的实参收集到最后一个形参中. 

例如 ,如果上面的函数还需要一个表示披萨尺寸的实参, 必须将形参放在形参 *toppings的前面'

def make_pazzle(size,*toppings ):
    print("\nMaking a  "+str(size)+
    "-inch pizza with the following toppings")
    for topping in toppings:
        print("- "+topping)

make_pazzle(16,'pepperoni')
make_pazzle(12,'mushrooms','green peppers ','extra cheese')

输出结果 :

Making a16-inch pizza with the following toppings
- pepperoni

Making a12-inch pizza with the following toppings
- mushrooms
- green peppers 
- extra cheese

基于上述函数定义 , python将收到的第一个值存储在形参size 中,并将其他的所有值都存储在元组toppings 中.

1.2使用任意数量的关键字实参

有时候 ,需要接受任意数量的实参, 但预先不知道传递的函数会是什么样的信息 .在这种情况下,可以将函数编写成能够接受任意数量的键值对 ---调用语句提供了多少就接受多少 . 一个这样的实例是创建用户简介 :

def build_profile(first,last ,**user_info):
    profile ={}
    profile['first_name'] = first
    profile['last_name'] = last
    for key ,value in user_info.items():
        profile[key] = value
    return profile
user_profile = build_profile('albert','einstein',location = 'princeton',filed = 'physics')
print(user_profile)

猜你喜欢

转载自blog.csdn.net/qq_41661809/article/details/81070073