Python- 函数 - 传递任意数量的参数

liftword5个月前 (01-13)技术文章43


收集任意位置参数:

有时,你不会提前知道一个函数需要多少个参数。

Python 允许您在参数名称前使用星号 * 收集任意数量的位置参数。这会将所有其他参数打包到一个 Tuples 中。

示例:接受任意数量的浇头的 pizza-ordering 函数:

def make_pizza(*toppings):
    
    print(toppings)

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



>>


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

在此示例中,*toppings 参数将所有 topping 收集为元组。即使只有一个参数,它仍然会将其打包到一个 Tuples 中。

遍历任意参数:

可以循环访问收集的参数以对其执行操作,而不是直接打印元组。

def make_pizza(*toppings):
    
    print("\nMaking a pizza with the following toppings:")
    
    for topping in toppings:
        print(f"- {topping}")

make_pizza('pepperoni') 
# Output: Making a pizza with the following toppings: - pepperoni

make_pizza('mushrooms', 'green peppers', 'extra cheese') 
# Output: Making a pizza with the following toppings: - mushrooms - green peppers - extra cheese

混合位置参数和任意参数:

您可能需要接受 fixed 和 arbitrary 参数。

位置参数应该放在第一位,任意参数应该放在函数定义的末尾。

示例:向 pizza 函数添加 size 参数:

def make_pizza(size, *toppings):
    
    print(f"\nMaking a {size}-inch pizza with the following toppings:")

    for topping in toppings:
        print(f"- {topping}")

make_pizza(16, 'pepperoni')  
# Output: Making a 16-inch pizza with the following toppings: - pepperoni

make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese')  
# Output: Making a 12-inch pizza with the following toppings: - mushrooms - green peppers - extra cheese

在这里,第一个参数被视为披萨大小,而其余参数被打包到 *toppings 元组中。

使用任意关键字参数:

有时,您不知道将向函数传递什么样的信息 (键值对)。

使用双星号 ** 收集任意数量的关键字参数。Python 使用这些键值对创建字典。

示例:构建用户配置文件的函数:

def build_profile(first, last, **user_info):
    
    user_info['first_name'] = first
    user_info['last_name'] = last
    return user_info

user_profile = build_profile('albert', 'einstein', location='princeton', field='physics')

print(user_profile)
# Output: {'location': 'princeton', 'field': 'physics', 'first_name': 'albert', 'last_name': 'einstein'}

user_info 参数将其他键值对收集到字典中。该函数始终接受名字和姓氏,但其他信息(如位置和字段)是可选的。

组合位置参数、关键字参数和任意参数

您可以以不同的方式混合位置、关键字和任意参数来创建灵活的函数。

这在各种情况下都很有用,例如处理不同类型的用户输入或参数。

常见用法:在许多 Python 代码中,您会看到 *args(任意位置参数)和 **kwargs(任意关键字参数)来收集灵活的参数集。

相关文章

python字典中如何添加键值对

添加键值对首先定义一个空字典 1>>> dic={}直接对字典中不存在的key进行赋值来添加123>>> dic['name']='zhangsan'>>...

什么是Python 之 ? 22 dict字典键值对

Python Dictionaries 字典,其实也叫键值对俗话说 男女搭配干活不累,九台怎么男女形成配对呢?key是不能重复的{ "key1": value1, "key2&...

python碰撞检测与鼠标/键盘的输入

碰撞检测与鼠标/键盘的输入本章的主要内容:● 碰撞检测;● 当遍历一个列表时切勿对其进行修改;● Pygame 中的键盘输入;● Pygame 中的鼠标输入。碰撞检测负责计算屏幕上的两个物体何时彼此接...

深入了解python字典的有序特性

字典字典有序还是无序初次接触python的时候,那时候用的python版本是2.7, 字典是无序的,就是说你update一个字典,新加的键值对不一定出现在字典的末尾,而是有可能出现在其他地方,popi...

Python教程-更改字典键和值

作为软件开发者,我们总是努力编写干净、简洁、高效的代码。Python 字典是该语言中最通用的数据结构之一,允许你以键值格式存储和访问数据。然而,你可能需要在你的程序中的某个时刻修改字典的键或值。在这篇...