zl程序教程

您现在的位置是:首页 >  后端

当前栏目

Python函数可变参数详解

Python 详解 函数 参数 可变
2023-06-13 09:12:01 时间
在实际使用函数时,可能会遇到 不知道函数需要接受多少个实参 的情况,不过好在 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