在本教程中,我将重点介绍Python中的参数( *args
)和关键字参数( *kwargs
)。
我将教你什么是args和kwargs,最重要的是,如何使用它们-即如何在函数中接受无限数量的参数和关键字参数。
什么是精氨酸?
*args
用于传递非关键字参数。 非关键字示例 参数是fun(3,4), fun("foo","bar")
。
*args
通常用作一种措施,如果我们不知道将有多少参数传递给函数,则可以防止程序崩溃。 这在C ++和其他编程语言中使用。
什么是Kwargs?
**kwargs
是关键字参数的字典。 **
允许我们传递任意数量的关键字参数。 关键字参数基本上是字典。
关键字示例 参数是fun(foo=2,bar=7)
。
**kwargs
就像 *args
除非您在函数中声明变量和数量 论点。
在哪里使用Args和Kwargs
当您要执行以下操作时,Args和kwargs很有用:
- 减少代码重写。
- 使您的代码可读。
- 重用您的代码
在函数中使用Args和Kwargs
让我们看一下如何在函数中使用kwargs和args。
精氨酸
下面的函数接受三个参数。 这三个参数已经明确定义,因此或多或少都会导致程序错误。
def add(a, b,c):
print(a+b+c)
print add(2,3,4)
让我们运行该函数。 该函数将三个数字相加,给出以下输出:
Output
9
如果我们要在函数中传递四个参数而不是必需的三个参数,该怎么办? 我们将收到如下所示的错误。
这是因为在函数中只定义了三个参数,但是在调用函数时我们已经传递了四个位置参数。
def add(a, b,c):
print(a+b+c)
print add(2,3,4,5)
Output
TypeError: add() takes 3 positional arguments but 4 were given
在下面的第二个示例中, *
用于非关键字参数,并传递给函数。 除了定义参数之外,我们用单个参数( *args
)替换a
, b
和c
。
请注意, *args
的使用如何使您轻松使用任意数量的参数而无需更改代码。 *args
为您的代码提供了更大的灵活性,因为将来您可以拥有任意数量的参数。
def add(*args):
total = 0
for arg in args:
total+=arg
print total
Scenario 1
print add(1,2,5)
Output
8
Scenario 2
print add(1,2,5,6)
output
14
Scenario 3
print add(1,2,5,8)
Output
16
更多例子
创建一个简单的函数,如下所示:
def func(*args):
# *args means for however many arguments you take in, it will catch them all
for arg in args:
print arg
使用整数和字符串的组合测试功能:
def func(*args):
# *args means for however many arguments you take in, it will catch them all
for arg in args:
print arg
print func(11,3,4,5,"tuts")
Output
11
3
4
5
tuts
如果我们将列表作为参数传递怎么办? 通过将先前的参数替换为列表l = [11,3,4,5,"tuts]
来用列表测试该函数。
def func(*args):
# *args means for however many arguments you take in, it will catch them all
for arg in args:
print arg
l = [11,3,4,5,"tuts"]
print func(l)
This prints the list as a whole,
This is because its interpreting the list as one item.
Output
[11,3,4,5,"tuts]
在上面的示例中,您还可以使用*args
解压缩列表或元组中已经存在的参数,以便将列表中的所有元素作为不同的参数传递。
使用相同的功能:
def func(*args):
# *args means for however many arguments you take in, it will catch them all
for arg in args:
print(arg)
l = [11,3,4,5,"tuts"]
print(func(*l))
The * will unpack the list and output each individual list item.
Output
11
3
4
5
tuts
夸格斯
Kwargs允许您将关键字参数传递给函数。 当您不确定将在函数中传递的关键字参数的数量时,将使用它们。
编写函数my_func
并将(x= 10, y =20)
作为关键字传递 参数如下所示:
def my_func(x=10,y=20):
print x,y
This prints out the values of x and y
Output
10,20
Kwargs可用于解包字典键,值对。 这是使用双星号( **
)完成的。 重要的是要注意,每个键都必须与一个值匹配。
这是一个典型的示例。 下面的函数将国家作为键,并将其首都作为值。 然后,它打印出一条语句,该语句遍历kwarg,并将每个关键字映射到为其分配的值。
def capital_cities(**kwargs):
# initialize an empty list to store the result
result = []
for key, value in kwargs.items():
result.append("The capital city of {} is {} .format (key,value)
return result
您可以使用所需的任何参数来调用该函数。
def capital_cities(**kwargs):
# initialize an empty list to store the result
result = []
for key, value in kwargs.items():
result.append("The capital city of {} is {} .format (key,value)
return result
print capital_city(China = "Beijing",Cairo = "Egypt",Rome = "Italy"))
output
['The capital city of China is Beijing', 'The capital city of Cairo is Egypt','The capital city of Rome is Italy']
对于更复杂的示例,假设我们有一个类似于以下内容的客户模型:
class Customer( models.Model ):
first_name = models.CharField(max_length = 100, null = True)
last_name = models.CharField(max_length = 100)
username =models.Charfield(max_length =100)
email = models.EmailField(max_length = 100)
password = models.CharField(max_length =100)
您可以使用kwargs进行数据输入和来自模型对象的数据查询。 让我们编写一个功能视图以创建新客户。
kwargs = {"first_name":"John","last_name":"Doe",
"username': "johndoe","email"johndoe@gmail.com",
"password":"1234"}
new_user = User(**kwargs)
new_user.save()
这是对刚刚使用kwargs创建的客户执行查询的方法。
filter_customer = {
'email':johndoe@gmail.com,
'username': johndoe,
}
Customer.objects.filter(**filter_customer)
在函数中同时使用Args和Kwargs
在同一函数定义中同时使用args和kwargs时, *args
必须出现在**kwargs
之前。
class MyFunction(Foo):
def __init__(self, *args, **kwargs):
print 'my function'
super(MyFunction, self).__init__(*args, **kwargs)
例:
def Func(*args,**kwargs):
for arg in args:
print arg
for item in kwargs.items():
print item
请记住, args
应该先于kwargs
。
def Func(*args,**kwargs):
for arg in args:
print arg
for item in kwargs.items():
print item
print Func(1,x=7,u=8)
Output
1
('x', 7)
('u', 8)
结论
我希望本教程可以帮助您了解args和kwargs。
以下是使用args和kwargs时要记住的一些提示:
-
*args
和**kwargs
是在函数中使用的特殊语法,用于将可变数量的参数传递给函数。 -
*args
之前发生**kwargs
在函数定义。
-
*args
和**kwargs
最适用于输入数量保持相对较小的情况。 - 您可以使用任意名称。
args
和kwargs
仅是约定俗成的,不是kwargs
。 例如,可以使用*foo
代替*args
或**foo
代替**kwargs
。
官方的Python 文档提供了很多信息以供进一步研究。 此外,不要犹豫,看看我们在市场上有哪些可供出售和研究的东西 ,也不要犹豫,使用下面的提要来问任何问题并提供宝贵的反馈。
翻译自: https://code.tutsplus.com/articles/understanding-args-and-kwargs-in-python--cms-29494