网站关键词seo排名,手机wordpress的文章分类,宁夏网站开发公司,网站建设贰金手指科捷9在实际使用函数时#xff0c;可能会遇到“不知道函数需要接受多少个实参”的情况#xff0c;不过好在 Python 允许函数从调用语句中收集任意数量的实参。例如#xff0c;设计一个制作披萨的函数#xff0c;我们知道#xff0c;披萨中可以放置很多种配料#xff0c;但无法…在实际使用函数时可能会遇到“不知道函数需要接受多少个实参”的情况不过好在 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:- pepperoniMaking 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] firstprofile[last_name] lastfor key, value in user_info.items():profile[key] valuereturn profileuser_profile build_profile(albert, einstein, locationprinceton, fieldphysics)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,locationprinceton, fieldphysics)运行结果为first:albert last:einsteinage:29TEL:123456location : princetonfield : physics