Contents

조회 수 3793 댓글 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
번호 분류 제목 글쓴이 날짜 조회 수
49 Develop [android] AlertDialog 메시지 창 띄우기 hooni 2015.07.09 2061
48 Develop [ios] NSData to NSString (NSString to NSData) hooni 2015.07.21 2033
47 Develop [c] 이진 탐색 두 가지 코드 (재귀/반복) file hooni 2015.06.26 2033
46 System/OS 개인적으로 쓰고 있는 bash_profile hooni 2015.01.16 2020
45 Develop [ios] SBCampanion App 초안 file hooni 2015.09.16 2018
44 Develop [ios] UIWebView에서 로컬에 있는 html 파일 불러오기 hooni 2015.02.10 2009
43 Develop [ios] 새로 만들고 있는 DateMemo file hooni 2016.07.12 1903
42 Develop [ios] NSNotificationCenter 초간단 사용 예~ ㅋㄷ hooni 2015.06.26 1863
41 Develop [ios] 문자열로 함수 실행하기 (eval 함수처럼) hooni 2015.02.10 1846
40 Develop [ios] WWDC 2015 샘플 소스 코드 통합파일 hooni 2015.07.20 1843
39 Develop [ios] Touch ID 적용 샘플 코드 (예제) file hooni 2015.02.23 1842
38 Develop [ios] iOS 8 개발자가 우선 알아야 할 3가지 file hooni 2014.10.02 1796
Board Pagination Prev 1 ... 90 91 92 93 94 95 96 97 98 99 Next
/ 99