본문 바로가기
C++ 200제/코딩 IT 정보

파이썬 함수 예제 9개, 가변인자 *args **kwargs 포함

by vicddory 2019. 5. 19.

파이썬 함수 확장 개념입니다. 먼저 *args, **kwargs 를 간략히 정리하면 이렇습니다.


  • *args - 함수 전달 인자를 튜플 형태로 받음
  • **kwargs - 함수 전달 인자를 딕셔너리로 받음
  • 공통 - 가변 인자로 전달 받음, 인수 개수는 매번 다를 수 있음




예제 1. test_1(x, y, z)

1
2
3
4
5
6
7
8
def test_1(x, y, z):
    print(x, y, z, end='\n', sep=',')
 
test_1(123)
test_1(x=1, y=2, z=3)
test_1(1, y=2, z=3)
test_1(12, z=3)
test_1(x=1, z=3, y=2)
cs




파이썬 함수 인자 x, y, z 를 설정하는 여러 예시입니다.

2. test_2(x, y=0, z=0)

1
2
3
4
5
6
7
8
9
def test_2(x, y=0, z=0):
    print(x, y, z)
 
test_2(1)
test_2(12)
test_2(123)
test_2(x=1, y=2, z=3)
test_2(x=1, y=2)
test_2(x=1, z=3)
cs




함수 인자 기본 값은 y=0, z=0 입니다. 함수 호출 시, y, z 값을 설정하지 않으면 기존에 설정된 값이 사용됩니다.


3. test_3(*args)

1
2
3
4
5
6
7
8
def test_3(*args):
    print(args)
    # print(args, type(args))  # 되는 코드
 
test_3(1)
test_3(12)
test_3(123)
test_3(123'hello')
cs




*args 함수 인자 형태라면, 가변인자이며, 파이썬 튜플 형태로 받습니다. 인자 개수는 정해져 있지 않으므로 위와 같은 4번의 함수 호출 방법은 모두 정상입니다.


4. test_4(*args)

1
2
3
4
5
6
7
8
def test_4(*args):
    print(*args)
    # print(*args, type(args))  # 안 되는 코드
 
test_4(1)
test_4(12)
test_4(123)
test_4(123'hello')
cs




3번과 다른 점은 출력할 때 ( ) 괄호가 빠졌습니다. 튜플로 받아 출력하는 것과 개별 요소를 받아 출력하는 것의 차이입니다. 예제 1, 2번 처럼 괄호 ( ) 없이 출력됩니다.

5. test_5(*args)

1
2
3
4
5
6
7
8
9
def test_5(*args):
    for i in args:
        print(i, end=',')
    print()
 
test_5(1)
test_5(12)
test_5(123)
test_5(123'hello')
cs




Python Tuple 형태로 받은 인자를 for문에서 하나씩 출력합니다. 함수 내부에 for문 선언이 가능한 것도 확인됩니다.


6. test_6(*args)

1
2
3
4
5
6
7
8
9
def test_6(*args):
    a = list(args)
    a.append(type(args))
    print(*a)  # *를 붙여서 요소 개별적으로 전달 가능
 
test_6(1)
test_6(12)
test_6(123)
test_6(123'hello')
cs




위 설명처럼 진짜로 가변인자를 파이썬 tuple 형태로 받는지 확인합니다. * 를 붙여 개별요소 전달해 출력합니다.


7. test_7(x, y, *args)

1
2
3
4
5
6
7
8
9
def test_7(x, y, *args):
    print(x, y, args)
    # print(x, y, *args)
 
test_7(12)
test_7(123)
test_7(123'hello')
test_7(x=1, y=2)
test_7(y=2, x=1)
cs




파이썬 인자 x, y는 반드시 받아야 하며, 이후 함수 인자는 가변적입니다. 즉, 최소한 인자가 2개 필요한 것입니다. 예제 1번, 5번이 합쳐진 형태입니다.

8. test_8(**kwargs)

1
2
3
4
5
6
7
8
9
def test_8(**kwargs):
    print(kwargs)
 
def test_9(**kwargs):
    # test_8(args=kwargs)
    test_8(**kwargs)
 
test_8(color='red', value=1)
test_9(color='red', value=1)
cs




**kwargs 는 가변인자를 딕셔너리(dictionary)로 받습니다. 그래서 인자를 전달할 때, key-value 형태로 인자를 전달합니다. 위 예제에서 key 는 color, value는 정수입니다.


9. test_0(x, y, **kwargs)

1
2
3
4
5
6
7
def test_0(x, y, **kwargs):
    print(x, y, kwargs)
 
test_0(12, color='red', value=1)
test_0(1, y=2, color='red', value=1)
test_0(x=1, y=2, color='red', value=1)
test_0(color='red', value=1, x=1, y=2)
cs




예제 7번과 비슷합니다. 8번에서 확인한 인자 전달 방법을 응용합니다. 마찬가지로 최소 인자는 2개입니다.



관련 글


파이썬 리스트 다루는 슬라이싱 예제 6개 slicing


파이썬 배열 역순(거꾸로) 출력, reversed, slice notation


파이썬 정수 최대값 구하기 소스 2개, random 함수



ⓒ written by vicddory

댓글