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

liftword6个月前 (01-13)技术文章50


收集任意位置参数:

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

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教程-更改字典键和值

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

值得推荐的编程练手项目有哪些?Python、java、html多种语言都有

本文原创并首发于公众号【Python猫】,未经授权,请勿转载。原文地址:https://mp.weixin.qq.com/s/ObDK4Mt8adL4-De354rMuQ今天,猫哥要推荐一本非常著名的...

Python - 爬虫之Selenium

一、Selenium 的介绍Selenium 是一个 Web 自动化测试工具,最初是为网站自动化测试而开发,Selenium 可以直接调用浏览器,它支持所有主流的浏览器(包括 PhantomJS 这些...