Python:什么是*args 和**kwargs?
我们可能会遇到类似这样的 Python 函数定义:
def a_function(*args, **kwargs):
...
星号表示可以接收可变长度参数。(args
和kwargs
名称无关紧要——它们只是约定俗成的,分别代表“参数”和“关键字参数”。可以使用任何合适的参数名称。)
假设我们需要一个功能让用户分享他们的爱好,但我们事先不知道特定用户会有多少个爱好:
def my_hobbies(*hobbies):
print("My hobbies: " + ", ".join(hobbies))
我们的函数现在接受一个或多个参数:
>>> my_hobbies('reading', 'writing')
My hobbies: reading, writing
>>> my_hobbies('reading', 'writing', 'hiking', 'learning Python')
My hobbies: reading, writing, hiking, learning Python
方便的是,我们还可以通过传递元组来调用我们的函数,使用类似的星号语法:
>>> some_hobbies = ('reading', 'writing', 'hiking', 'learning Python')
>>> my_hobbies(*some_hobbies)
My hobbies: reading, writing, hiking, learning Python
现在假设我们想要一个功能,使用户能够在各个类别中分享他们喜欢的东西,但我们事先不知道给定用户会选择多少个类别:
def my_faves(**favorites):
print("My favorite things...")
for category, fave in favorites.items():
print(f"{category}: {fave}")
我们的函数现在接受一个或多个关键字参数:
>>> my_faves(Color='green', Fruit='persimmon')
My favorite things...
Color: green
Fruit: persimmon
>>> my_faves(Season='winter', Language='Python', Website='dev.to')
My favorite things...
Season: fall
Language: Python
Website: dev.to
我们还可以通过传递字典来调用我们的函数,使用类似的双星号语法:
>>> some_faves = {"Animal": "whale", "Summer Hobby": "hiking"}
>>> my_faves(**some_faves)
My favorite things...
Animal: whale
Summer Hobby: hiking
函数可以混合使用形式参数、变长参数和变长关键字参数来定义。当这样做时,它们必须按照以下顺序出现在定义中:
def a_function(arg, *args, **kwargs):
...
更多信息可以在Python 文档中找到。
这有帮助吗?我帮你节省了时间吗?
🫖 给我买杯茶!☕️
鏂囩珷鏉ユ簮锛�https://dev.to/adamlombard/python-what-are-args-and-kwargs-35co