조회 수 1670 추천 수 0 댓글 0
?

단축키

Prev이전 문서

Next다음 문서

크게 작게 위로 아래로 댓글로 가기 인쇄
?

단축키

Prev이전 문서

Next다음 문서

크게 작게 위로 아래로 댓글로 가기 인쇄

python 코드를 보다보면

*args, **kwargs 를 심심치 않게 본다.

그냥 막연하게 "어떤 파라미터를 몇개를 받을지 모르는 경우 사용한다" 라고 알고 있었지만

자세히 설명한 예 가 있어서 소개한다.



*args

- 파라미터를 몇개를 받을지 모르는 경우 사용한다. args 는 튜플 형태로 전달된다.

예)

def print_param(*args):
    print args
    for p in args:
        print p

print_param('a', 'b', 'c', 'd')
#('a', 'b', 'c', 'd')
#a
#b
#c
#d


**kwargs

- 파라미터 명을 같이 보낼 수 있다. kwargs는 딕셔너리 형태로 전달된다.

def print_param2(**kwargs):
    print kwargs
    print kwargs.keys()
    print kwargs.values()

    for name, value in kwargs.items():
        print "%s : %s" % (name, value)

print_param2(first = 'a', second = 'b', third = 'c', fourth = 'd')

#{'second': 'b', 'fourth': 'd', 'third': 'c', 'first': 'a'}
#['second', 'fourth', 'third', 'first']
#['b', 'd', 'c', 'a']
#second : b
#fourth : d
#third : c
#first : a



그러면 두개를 같이 쓰는 경우는??

def print_param3(*args, **kwargs):
    print args
    print kwargs

print_param3('a', 'b')
#('a', 'b')
#{}

print_param3(third = 'c', fourth = 'd')
#()
#{'fourth': 'd', 'third': 'c'}

print_param3('a', 'b', third = 'c', fourth = 'd')
#('a', 'b')
#{'fourth': 'd', 'third': 'c'}



응용 해 보자

def print_param4(a, b, c):
    print a, b, c

p = ['a', 'b', 'c']
print_param4(*p)
#a b c

p2 = {'c' : '1', 'a' : '2', 'b' : '3'}
print_param4(**p2)
#2 3 1


[출처] https://www.geeksforgeeks.org/args-kwargs-python/

[참고] https://stackoverflow.com/questions/3394835/use-of-args-and-kwargs


?

List of Articles
번호 분류 제목 글쓴이 날짜 조회 수
825 Develop SVN 초간단 사용하기 hooni 2014.02.28 7674
824 Develop URI 인코딩, URL 인코딩 file hooni 2013.04.23 18894
823 Develop What is difference between Get, Post, Put and Delete? hooni 2018.02.28 1555
822 Develop XE Core 1.8.18 본문 작성시 태그(html) 사라지는 버그 file hooni 2016.04.21 1009
821 Develop XML, JSON, BSON, MSGPACK 장,단점 비교 file hooni 2017.01.11 2350
820 Develop ZBar 라이브러리를 이용한 바코드 스캔 앱 개발하기 file hooni 2015.01.01 1720
819 Develop [ajax] 샘플 코드와 한글처리에 대한 간단한 설명 hooni 2013.04.23 6867
818 Develop [ajax] 이벤트 코드 생성기 작업중.. ㅋㅋ file hooni 2013.04.23 7156
817 Develop [Android Error] The number of method references in a .dex file cannot exceed 64K hooni 2016.11.10 880
816 Develop [Android] 2010년에 만들었던 세미나 자료. file hooni 2013.05.28 64724
815 Develop [android] AlertDialog 메시지 창 띄우기 hooni 2015.07.09 978
814 Develop [android] Android N requires the IDE to be running with Java 1.8 or later 오류 hooni 2016.08.30 933
813 Develop [android] ArrayAdapter 테스트 파일 ㅎㅎ hooni 2013.04.23 45286
812 Develop [android] ArrayAdapter를 이용하여 출력하기 hooni 2013.04.23 47384
811 Develop [android] Calling activity function from separate class hooni 2016.11.15 1295
810 Develop [android] Canvas를 이용해 이미지 확대/축소 하기 hooni 2013.04.23 60786
Board Pagination Prev 1 2 3 4 5 ... 53 Next
/ 53