조회 수 3782 추천 수 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
번호 분류 제목 글쓴이 날짜 조회 수
75 Develop [js] Text 값을 클립보드에 복사하기 hooni 2020.10.10 2727
74 Develop [matlab] 정보은닉 스테가노그래피(Steganography) 수업 file hooni 2016.10.03 2712
73 Develop ZBar 라이브러리를 이용한 바코드 스캔 앱 개발하기 file hooni 2015.01.01 2705
72 Develop [web] 더 빠른 웹을 위한 프로토콜, 'HTTP/2' file hooni 2014.10.20 2657
71 Develop [ios] 스크린 캡쳐 (전원버튼 + 홈버튼) 호출 알아내기 hooni 2014.11.19 2597
70 Develop [c] FSN 온라인 코딩 테스트 (Sorting, Binary Search) file hooni 2015.06.26 2562
69 Develop [sh] html 안에 있는 img 다운 받는 쉘 스크립트 file hooni 2020.05.26 2557
68 Develop '2014 모바일 개발 트렌드' 발표자료입니다. file hooni 2014.10.02 2533
67 Develop [c] 파일명 또는 특정 패턴을 적용 file hooni 2016.08.03 2404
66 Develop [c] 기막힌 정렬 코드 ㅋㄷ file hooni 2015.10.13 2390
65 Develop [ios] 오브젝티브C→스위프트, 코드 변환 손쉽게 file hooni 2015.08.07 2369
64 Develop [ios] Crashlytics, Fabfic 설치/설정 hooni 2016.07.21 2358
63 Develop 리팩토링 계획안 file hooni 2017.05.15 2345
62 Develop [ios] UIView 계층구조 hooni 2015.01.03 2317
61 Develop [ios] iOS 앱 아이콘을 만드는 유틸 file hooni 2015.01.03 2317
60 Develop [ios] UIWebView를 이용한 로컬 HTML 파일 표시 file hooni 2015.01.02 2300
Board Pagination Prev 1 ... 47 48 49 50 51 53 Next
/ 53