PYTHON函数(5)传递任意数量的实参

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

def make_pizza(*toppings):
    """打印顾客点的所有配料"""
    print(toppings)

make_pizza('pepperoni')
make_pizza('mushrooms','green peppers','extra cheese')

形参*toppings中的*让Python创建一个名为toppings的空元组,并将收到的所有值都封装到这个元组中。

('pepperoni',)
('mushrooms', 'green peppers', 'extra cheese')

现在我们可以将这条print语句替换为一个循环,对配料表进行遍历,并对顾客点的pizza进行描述

def make_pizza(*toppings):
    """打印顾客点的所有配料"""
    print("\nMaking a pizza with the following toppings:")
    for topping in toppings:
        print("- "+topping)

make_pizza('pepperoni')
make_pizza('mushrooms','green peppers','extra cheese')

不管函数收到的实参是多少个,这种语法都适用

Making a pizza with the following toppings:
- pepperoni

Making a pizza with the following toppings:
- mushrooms
- green peppers
- extra cheese

1、结合使用位置实参和任意数量的实参

如果要让函数接受不同类型的实参,必须在函数定义中将接纳任意数量实参的形参放在最后。

python先匹配位置实参和关键字实参,再将余下的实参都收集到最后一个形参中。

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

def make_pizza(size,*toppings):
    """概述要制作的pizza"""
    print("\nMaking a "+str(size)+"-inch pizza with the following toppings:")
    for topping in toppings:
        print("- "+topping)

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

结果

Making a pizza with the following toppings:
- pepperoni

Making a pizza with the following toppings:
- mushrooms
- green peppers
- extra cheese

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',field='pyysics')
print(user_profile)

结果

{'first_name': 'albert', 'last_name': 'einstein', 'location': 'princeton', 'field': 'pyysics'}

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值