当我们看到任何包含 * args和 ** kwargs的函数的文档时,您是否想过 - 在该函数内部传递的这些奇怪参数是什么?
举个例子:
function(params, *args, **kwargs)
作为初学者,您可能会对如何使用该函数或在调用该函数时作为参数传递什么来代替 * args和 ** kwargs感到困惑。
不用担心,在本教程中我们将讨论*args\**kwargs它们的含义以及它们在函数中的用途,并提供示例以帮助您更好地理解。
我们将看到示例中使用的*和**(拆包运算符)的应用。
介绍
Python 中的函数帮助我们编写可重复使用的代码,以在各种操作中执行特定任务。让我们定义一个打印字符名称的函数。
示例:function打印字符名称
def characters(name1, name2, name3):
print(name1, name2, name3)
characters("Iron Man", "Black Panther", "Captain America")
输出
Iron Man Black Panther Captain America
上面的函数characters采用 3 个位置参数name1, name2,name3并简单地打印名称。
如果我们传递的参数数量超过它所需要的数量怎么办
def characters(name1, name2, name3):
print(name1, name2, name3)
characters("Iron Man", "Black Panther", "Captain America", "Hulk")
输出将是一个错误
TypeError: characters() takes 3 positional arguments but 4 were given
错误是由于函数内部传递的额外参数引起的,它只接受三个参数。
因为我们需要在函数内部再传递一个参数character才能使代码无误地运行。但是,这不是最佳做法。例如,假设您正在处理一个项目,您需要在调用特定函数时动态添加多个参数。在这种情况下你应该怎么做?
有一种方法可以处理这种情况。
*参数的使用
*args只是缩短了arguments。
*之前的星号确保args参数具有可变长度。
*args是非关键字参数或位置参数。
通过使用*args,您可以在调用函数时传递任意数量的参数。
*args示例:在函数定义中使用
def friends(*args):
print(args)
friends("Sachin", "Rishu", "Yashwant", "Abhishek")
输出
('Sachin', 'Rishu', 'Yashwant', 'Abhishek')
得到了Tuple,因为当我们使用*args该函数时,会将参数作为tuple.
检查类型
def friends(*args):
print(type(args))
print(args)
friends("Sachin", "Rishu", "Yashwant", "Abhishek")
输出
<class 'tuple'>
('Sachin', 'Rishu', 'Yashwant', 'Abhishek')
我们还可以将常规参数与*args.
示例:在函数定义中使用常规参数和 args
def friends(greet, *args):
for friend in args:
print(f"{greet} to Python, {friend}")
greet = "Welcome"
friends(greet, "Sachin", "Rishu", "Yashwant", "Abhishek")
输出
Welcome to Python, Sachin
Welcome to Python, Rishu
Welcome to Python, Yashwant
Welcome to Python, Abhishek
注意:你可以使用任何你想要的名字来代替 args,只要你在 * 它前面加上一个。
示例:使用不同的名称而不是 args
def dog(prefix, *german_shepherd):
for breed in german_shepherd:
print(f"The {prefix} is {breed}.")
prefix = "breed"
dog(prefix, "Labrador", "GSD", "Chihuahua")
输出
The breed is Labrador.
The breed is GSD.
The breed is Chihuahua.
有一个例外:当将常规参数作为*args参数传递给函数时,永远不要*args在常规参数之前传递。
示例:*args在函数内部使用常规参数之前
def heroes(*characters, country):
for character in characters:
print(f"{character} is from {country}.")
country = "USA"
heroes(country, "Iron Man", "Captain America", "Spiderman")
输出
TypeError: heroes() missing 1 required keyword-only argument: 'country'
我们得到 a 是因为我们不能在常规参数之前TypeError通过。*args
如果我们更改代码并移动函数内部传递的参数,将不会出现错误。
def heroes(country, *characters):
for character in characters:
print(f"{character} is from {country}.")
country = "USA"
heroes(country, "Iron Man", "Captain America", "Spiderman")
输出
Iron Man is from USA.
Captain America is from USA.
Spiderman is from USA.
上面的代码执行没有任何错误。
**kwargs 的用法
**kwargs为Keyword argument缩短。
现在您已经熟悉*args并了解它的实现,与*args不同的是,**kwargs它采用关键字或命名参数。
在**kwargs中,我们使用**双星号允许我们传递关键字参数。
**kwargs示例:在函数定义中的使用
def hello(**kwargs):
print(type(kwargs))
for key, value in kwargs.items():
print(f"{key} is {value}.")
hello(One = "Red", two = "Green", three = "Blue")
输出
<class 'dict'>
One is Red.
two is Green.
three is Blue.
type是字典**kwargs,key-value即接受的参数。
**kwargs示例:在函数定义中使用常规参数和一起
def hello(write, **kwargs):
print(write)
for key, value in kwargs.items():
print(f"{key} is {value}.")
write = "RGB stands for:"
hello(write, One = "Red", two = "Green", three = "Blue")
输出
RGB stands for:
One is Red.
two is Green.
three is Blue.
就像*args,可以选择任何名称而不是**kwargs
示例:使用不同的名称而不是 kwargs
def hello(write, **color):
print(write)
for key, value in color.items():
print(f"{key} is {value}.")
write = "RGB stand for:"
hello(write, One = "Red", two = "Green", three = "Blue")
输出
RGB stand for:
One is Red.
two is Green.
three is Blue.
注意:我们不能在函数定义中传递**kwargsbefore否则,我们会得到一个.*argsSyntaxError
我们可以在函数定义中使用所有三种类型的参数,在这个例子中,我们将看到解包运算符*和**的使用。
def friends(greet, *args, **kwargs):
for names in args:
print(f"{greet} to the Programming zone {names}")
print("\nI am Veronica and I would like to announce your roles:")
for key, value in kwargs.items():
print(f"{key} is a {value}")
greet = "Welcome"
names = ["Sachin", "Rishu", "Yashwant", "Abhishek"]
roles = {"Sachin":"Chief Instructor", "Rishu":"Engineer",
"Yashwant":"Lab Technician", "Abhishek":"Marketing Manager"}
friends(greet, *names, **roles)
输出
Welcome to the Programming zone Sachin
Welcome to the Programming zone Rishu
Welcome to the Programming zone Yashwant
Welcome to the Programming zone Abhishek
I am Veronica and I would like to announce your roles:
Sachin is a Chief Instructor
Rishu is a Engineer
Yashwant is a Lab Technician
Abhishek is a Marketing Manager
您会注意到names使用了roles上面代码中调用的变量。
但是,当我们在函数内部传递它们时,我们将它们放在names变量*之前和roles变量**之前。
*单星号用于解包 iterable,**双星号用于解包字典。