Contents

조회 수 1559 댓글 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



?

  1. [css] z-index에 설정할 수 있는 최대값?

    Date2013.12.20 CategoryDevelop Byhooni Views14720
    Read More
  2. [js] jQuery plugin 요약

    Date2013.12.20 CategoryDevelop Byhooni Views10703
    Read More
  3. [php] GregorianToJD(), JDToGregorian() 함수 내용

    Date2013.12.25 CategoryDevelop Byhooni Views10596
    Read More
  4. [php] 하루 전 날짜 쉽게 구하기.

    Date2013.12.25 CategoryDevelop Byhooni Views12219
    Read More
  5. [js] AngularJS를 소개합니다.

    Date2014.01.06 CategoryDevelop Byhooni Views13017
    Read More
  6. [ios] UIButton multi-line iOS7

    Date2014.01.09 CategoryDevelop Byhooni Views11437
    Read More
  7. [php] substr() 한글 자를 때 깨짐 방지

    Date2014.01.09 CategoryDevelop Byhooni Views20367
    Read More
  8. [ios] UIWebView 쿠키 유지

    Date2014.01.16 CategoryDevelop Byhooni Views11708
    Read More
  9. [ios] UIWebView에서 NSURLRequest에 Cookie 실어 보내기

    Date2014.01.16 CategoryDevelop Byhooni Views14861
    Read More
  10. [js] 주소표시줄 URL 읽어오기 (변경까지)

    Date2014.01.21 CategoryDevelop Byhooni Views1
    Read More
  11. [ios] 네트워크 인디케이터(NetworkActivityIndicator) 작동

    Date2014.01.24 CategoryDevelop Byhooni Views12493
    Read More
  12. [ios] iOS 6.0 이상 회전 하기 (이전 버전과 비교 변경 부분)

    Date2014.01.27 CategoryDevelop Byhooni Views34188
    Read More
Board Pagination Prev 1 ... 47 48 49 50 51 52 53 54 55 56 ... 71 Next
/ 71