본문 바로가기
파이썬

파이썬에서 별표 *는 무엇을 의미합니까?

by º기록 2020. 10. 27.
반응형

*는 C에서와 같이 Python에서 특별한 의미가 있습니까? Python Cookbook에서 다음과 같은 함수를 보았습니다.

def get(self, *a, **kw)

저에게 설명해 주시거나 답변을 찾을 수있는 곳을 알려주시겠습니까 (Google은 *를 와일드 카드 문자로 해석하므로 만족스러운 답변을 찾을 수 없습니다).

 

해결 방법

 


* identifier 형식이 present, it is initialized to a tuple receiving any excess positional parameters, defaulting to the empty tuple. If the form **identifier is present, it is initialized to a new dictionary receiving any excess keyword arguments, defaulting to a new 빈 사전.


위치 및 키워드 인수가 무엇인지 알고 있다고 가정하면 다음과 같은 몇 가지 예가 있습니다.

예 1 :

# Excess keyword argument (python 2) example:
def foo(a, b, c, **args):
    print "a = %s" % (a,)
    print "b = %s" % (b,)
    print "c = %s" % (c,)
    print args

foo(a="testa", d="excess", c="testc", b="testb", k="another_excess")

위의 예에서 볼 수 있듯이 foo 함수의 서명에는 a, b, c 매개 변수 만 있습니다. d k 가 존재하지 않으므로 args 사전에 배치됩니다. 프로그램의 출력은 다음과 같습니다.

a = testa
b = testb
c = testc
{'k': 'another_excess', 'd': 'excess'}

예 2 :

# Excess positional argument (python 2) example:
def foo(a, b, c, *args):
    print "a = %s" % (a,)
    print "b = %s" % (b,)
    print "c = %s" % (c,)
    print args

foo("testa", "testb", "testc", "excess", "another_excess")

여기에서 위치 인수를 테스트하고 있으므로 초과 인수는 끝에 있어야하며 * args 는이를 튜플로 압축하므로이 프로그램의 출력은 다음과 같습니다.

a = testa
b = testb
c = testc
('excess', 'another_excess')

함수의 인수에 사전 또는 튜플을 압축 해제 할 수도 있습니다.

def foo(a,b,c,**args):
    print "a=%s" % (a,)
    print "b=%s" % (b,)
    print "c=%s" % (c,)
    print "args=%s" % (args,)

argdict = dict(a="testa", b="testb", c="testc", excessarg="string")
foo(**argdict)

인쇄물:

a=testa
b=testb
c=testc
args={'excessarg': 'string'}

def foo(a,b,c,*args):
    print "a=%s" % (a,)
    print "b=%s" % (b,)
    print "c=%s" % (c,)
    print "args=%s" % (args,)

argtuple = ("testa","testb","testc","excess")
foo(*argtuple)

인쇄물:

a=testa
b=testb
c=testc
args=('excess',)

 

참조 페이지 https://stackoverflow.com/questions/400739

 

 

반응형

댓글