Computer >> 컴퓨터 >  >> 프로그램 작성 >> Python

Python에서 인수 패킹 및 풀기?

<시간/>

파이썬으로 프로그래밍을 조금 해봤다면 파이썬 함수에서 "**args"와 "**kwargs"라는 단어를 본 적이 있을 것입니다. 하지만 정확히 무엇입니까?

* 및 ** 연산자는 사용 위치에 따라 서로 보완적인 다른 작업을 수행했습니다.

따라서 -

와 같이 메서드 정의에서 사용할 때
def __init__(self, *args, **kwargs):
pass

위의 작업은 모든 인수를 args라는 튜플에 이 메서드 호출이 받는 하나의 단일 변수로 묶기 때문에 '패킹'이라고 합니다. args 이외의 이름을 사용할 수 있지만 args는 작업을 수행하는 가장 일반적이고 파이썬적인 방법입니다. 하나의 단일 변수를 넣어야 하는 이유를 이해하려면 아래 예를 고려하십시오.

세 개의 인수를 취하는 함수가 있고 함수에 대한 모든 인수를 포함하는 크기 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

따라서 파이썬 함수에 전달해야 하는 인수의 수를 모르는 경우 패킹을 사용하여 튜플의 모든 인수를 패킹할 수 있습니다.

#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] = 'TutorialsPoint'

#Unpacking args and calling func1()
func1(*args)

#Driver code
func2("I", "Love", "Coding")

결과

Argument One: Hello

Argument Two: TutorialsPoint

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와 같은 웹 프레임워크에서 뷰 함수에 변수 인수를 보내는 데 사용됩니다.

  • 변수 인수를 전달해야 하는 래퍼 함수에 사용됩니다.