用Python打包参数?
如果您完成了一点点的python编程工作,那么您会在python函数中看到“**args”和“**kwargs”两个词。但是它们到底是什么?
*和**运算符执行不同的操作,这取决于我们在何处使用,它们彼此互补。
因此,当我们在方法定义中使用它们时,例如-
def __init__(self, *args, **kwargs): pass
上面的操作称为“打包”,因为它将所有参数打包到一个单个变量中,此方法调用将其接收到一个称为args的元组中。我们可以使用除args之外的其他名称,但是args是最常用的pythonic方式。要了解为什么要放置一个变量,请请看以下示例:
假设我们有一个带有三个参数的函数,并且我们有一个大小为3的列表,其中包含该函数的所有参数。现在,如果我们只是简单地尝试将列表传递给该函数,则该调用将不起作用,并且会出现错误。
例子1
#function which takes three argument
def func(a,b,c):
print("{} {} {}".format(a, b, c))
#list of arguments
lst = ['python', 'java', 'csharp']
#passing the list
func(lst)结果
TypeError: func() missing 2 required positional arguments: 'b' and 'c'
一旦我们“选择”了变量,那么您就可以完成普通元组无法完成的工作。Args[0],args[1]和args[2]将分别给我们第一个,第二个和第三个参数。如果将args元组转换为列表,则可以执行修改,删除和更改其中的项目的操作。
要将这些打包参数传递给另一个方法,我们需要进行打包-
def __init__(self, *args, **kwargs): #some code here car(VehicleClass, self).__init__(self, *args, **kwargs) #some code below
同样,我们有*运算符,但是这次是在方法调用的上下文中。现在要做的是爆炸args数组,并调用该方法,就好像每个变量都是独立的一样。以下是另一个可以清楚理解的示例-
例子2
def func1(x, y, z):
print(x)
print(y)
print(z)
def func2(*args):
#Convert args tuple to a list so we can do modification.
args = list(args)
args[0] = 'HTML'
args[1] = 'CSS'
args[2] = 'JavaScript'
func1(*args)
func2('Python', 'Java', 'CSharp')结果
HTML CSS JavaScript
从上面的输出中,我们可以更改所有三个参数,然后再将它们传递给func1。
同样,我们可以解决example1中发现的TypeError消息。
示例:1_1
#function which takes three argument
def func(a,b,c):
print("{} {} {}".format(a, b, c))
#list of arguments
lst = ['python', 'java', 'csharp']
#passing the list
func(*lst)结果
python java csharp
因此,如果我们不知道需要将多少个参数传递给python函数,则可以使用packing将所有参数打包到一个元组中。
#Below function uses packing to sum unknown number of arguments
def Sum(*args):
sum = 0
for i in range(0, len(args)):
sum = sum + args[i]
return sum
#Driver code
print("Function with 2 arguments & Sum is: \n",Sum(9, 12))
print("Function with 5 arguments & Sum is: \n",Sum(2, 3, 4, 5, 6))
print("Function with 6 arguments & Sum is: \n",Sum(20, 30, 40, 12, 40, 54))结果
Function with 2 arguments & Sum is: 21 Function with 5 arguments & Sum is: 20 Function with 6 arguments & Sum is: 196
下面是另一个程序,用于演示打包和拆包两者的用法:
#function with three arguments
def func1(x,y,z):
print("Argument One: ",x)
print("\nArgument Two: ",y)
print("\nArgument Three: ",z)
#Packing- All arguments passed to func2 are packed into tuple *args
def func2(*args):
#To do some modification, we need to convert args tuple to list
args = list(args)
#Modifying args[0] & args[1]
args[0] = 'Hello'
args[1] = 'nhooo'
#Unpacking args and calling func1()
func1(*args)
#Driver code
func2("I", "Love", "Coding")结果
Argument One: Hello Argument Two: nhooo Argument Three: Coding
对字典使用**
# Program to demonstrate unpacking of dictionary items using **
def func(x,y,z):
print("Dicionary first item: ",x)
print("\nDictionary second item: ",y)
print("\nDictionary third item: ",z)
d = {'x': 27, 'y': 54, 'z': 81}
func(**d)结果
Dicionary first item: 27 Dictionary second item: 54 Dictionary third item: 81
应用领域
在套接字编程中使用,我们需要向服务器发送未知(无限)个请求。
在django之类的Web框架中使用,以发送变量参数以查看函数。
用于要求我们传递变量参数的包装函数。