*는 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
'파이썬' 카테고리의 다른 글
파이썬 팬더는 groupby의 평균을 얻습니다 (0) | 2020.10.28 |
---|---|
파이썬 Python에서 동일한 그래프에 목록 목록 그리기 (0) | 2020.10.28 |
파이썬 쉼표를 도트 팬더로 대체 (0) | 2020.10.27 |
파이썬에서 n 개의 문자로 채우는 방법 (0) | 2020.10.27 |
파이썬 Python의 RotatingFileHandler 사용 방법 (0) | 2020.10.27 |
댓글