Python函数可变参数详解
例如,设计一个制作披萨的函数,我们知道,披萨中可以放置很多种配料,但无法预先确定顾客要多少种配料。该函数的实现方式如下:
def make_pizza(*toppings): 打印顾客点的所有配料 print(toppings) make_pizza( pepperoni ) make_pizza( mushrooms , green peppers , extra cheese )
可以看到,make_pizza() 函数中,只包含一个形参 *toppings,它表示创建一个名为 toppings 的空元组,并将收到的所有值都封装到这个元组中。并且,函数体内的 print() 通过生成输出来证明 Python 既能够处理使用一个值调用函数的情形,也能处理使用三个值来调用函数的情形。
因此,上面程序的输出结果为:
( pepperoni ,)
( mushrooms , green peppers , extra cheese )
注意,如果函数参数中既要接收已知数量的实参,又要接收任意数量的实参,则必须遵循一个原则,即将接纳任意数量实参的形参放在最后。
这种情况下,Python 会先匹配位置实参,再将余下的实参收集到最后一个形参中。
仍以制作披萨为例,现在需要客人明确指明要购买披萨的尺寸,那么修改后的函数如下所示:
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 )
输出结果为:
Making a 16-inch pizza with the following toppings:
pepperoni
Making a 12-inch pizza with the following toppings:
mushrooms
green peppers
extra cheese
可以看到,Python 将收到的第一个值存储在形参 size 中,并将其他的所有值都存储在元组 toppings 中。
函数接收任意数量的关键字实参如果在调用函数时是以关键字参数的形式传入实参,且数量未知,则需要使函数能够接收任意数量的键值对参数。
举个例子:
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)
运行结果为:
{ first_name : albert , last_name : einstein , location : princeton , field : physics }
注意观察,函数 build_profile() 中,形参 **user_info 表示创建一个名为 user_info 的空字典,并将接受到的所有键值对都存储到这个字典中。
这里的 **user_info 和普通字典一样,我们可以使用访问其他字典那样访问它存储的键值对。
以上分别给大家介绍了如何实现让函数接收任意个(普通方式传递的)实参以及任意个关键字实参。其实,在实际编程中,这两种方式可以结合使用。例如:
def build_profile(first, last, *infos, **user_info): print(first,last) for info in infos: print(info) for key, value in user_info.items(): print(key, : ,value) build_profile( first:albert , last:einstein , age:29 , TEL:123456 ,location= princeton , field= physics )
运行结果为:
first:albert last:einstein
age:29
TEL:123456
location : princeton
field : physics
23083.html
python相关文章
- python常用面试题_Python+Selenium 常见面试题整理[通俗易懂]
- python中的type和object详解
- python recvfrom函数详解_recvfrom函数详解
- Python里divmod_python yield函数
- Python setattr()、getattr()、hasattr()函数用法详解
- Python连接redis笔记详解数据库
- 一个python自定义的加密解密函数详解编程语言
- Python实现截屏的函数详解编程语言
- Python抓妹子图+多进程详解编程语言
- python 通关sleep函数等待到明天再执行详解编程语言
- 通过python post提交数据的代码演示详解编程语言
- 发送email 带附件的Python代码详解编程语言
- python中对象、类型和元类之间的关系详解大数据
- Python函数——学习笔记详解编程语言
- Python中函数的参数传递与可变长参数详解编程语言
- python全栈开发-Day8 函数基础详解编程语言
- Python学习:5、if语句,while语句,函数详解编程语言
- python继续函数-练习(2017-8-3)详解编程语言
- python之面向对象详解编程语言
- python基础7之python3的内置函数详解编程语言
- Python_day11_闭包函数详解编程语言
- Python函数:一个简单的迭代详解编程语言
- python-函数作用域详解编程语言
- python-内置函数详解编程语言
- Python服务端面试—Mysql基础考点详解编程语言
- Python面试笔试题记录详解编程语言
- Python IDLE调试程序详解
- 闭包在python中的应用之translate和maketrans用法详解