码迷,mamicode.com
首页 > 编程语言 > 详细

python随笔12(传递任意数量的实参)

时间:2018-09-18 11:02:49      阅读:265      评论:0      收藏:0      [点我收藏+]

标签:方式   有一个   style   位置   函数   OWIN   user   gre   基于   

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

例如,来看一个制作披萨的函数,它需要接受很多的配料,但你无法预先确定顾客要多少种配料。下面函数只有一个形参*toppings,但不管调用语句提供了多少实参,这个形参都将它们统统收入囊中。

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

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

形参名*toppings中的星号让python创建一个名为toppings的空元组,并将收到的所有值都封装到这个元组中。函数体内的print语句通过生成输出来证明python能够处理使用一个值调用函数的情形,也能处理使用三个值来调用函数的情形。它以类似的方式处理不同的调用,注意python将实参封装到一个元组中,即便函数只收到一个值也是如此:

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

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

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

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

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

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

def make_pizza(size,*toppings):
    """概述要制作的披萨"""
    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)

基于上述函数定义,python将收到的第一个值存储在形参size中,并将其他的所有值都存储在元组toppings中。在函数调用中,首先指定表示披萨尺寸的实参,然后根据需要指定任意数量的配料。

Making a 16-inch pizza with the following toppings;
- pepperoni

Making a 12-inch pizza with the following toppings;
- mushrooms
- green peppers
- extra cheese

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

有时候,需要接受任意数量的实参,但预先不知道传递给函数的会是什么样的信息。在这种情况下,可将函数编写成能够接受任意数量的键—值对——调用语句提供了多少就接受多少。

一个这样的示例是创建用户简介:你知道你将收到有关用户的信息,但不确定会是什么样的信息。在下面的示例中,函数build_profile()接受名和姓,同时还接受任意数量的关键字实参:

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 = physics)
print(user_profile)

函数build_profile()的定义要求提供名和姓,同时允许用户根据需要提供任意数量的名称—值对。形参**user_info中的两个星号让python创建一个名为user_info的空字典,并将收到的所有名称—值对都封装到这个字典中。在这个函数中,可以像访问其他字典那样访问user_info中的名称—值对。

{first_name: albert, last_name: einstein, location: princeton, field: physics}

python随笔12(传递任意数量的实参)

标签:方式   有一个   style   位置   函数   OWIN   user   gre   基于   

原文地址:https://www.cnblogs.com/wf1017/p/9667227.html

(1)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!