///
Search

ํŒŒ์ด์ฌ *(์• ์Šคํ„ฐ๋ฆฌ์Šคํฌ)

๋ถ„๋ฅ˜
๋ฌธ๋ฒ•
์†์„ฑ
์ƒ์„ฑ์ผ
2022/01/27 21:22
์ตœ์ข… ์ˆ˜์ •
2022/01/27 21:24
๋ ˆํผ๋Ÿฐ์Šค : https://hwiyong.tistory.com/193

1. ๊ณฑ์…ˆ๊ณผ ๊ฑฐ๋“ญ์ œ๊ณฑ

โ€ข
๊ตณ์ด ์ฝ”๋“œ๋ฅผ ๋ถ™์ด์ง€ ์•Š์•„๋„ ๋‹ค๋“ค ์•„์‹ค๊ฑฐ๋ผ๊ณ  ์ƒ๊ฐํ•ฉ๋‹ˆ๋‹ค.
โ€ข
1 * 2 = 2
โ€ข
2 ** 2 = 4

2. ๋ฆฌ์ŠคํŠธ ํ™•์žฅ

โ€ข
๋ฅผ ์‚ฌ์šฉํ•˜์—ฌ ๋ฆฌ์ŠคํŠธ๋ฅผ ๊ฐ„๋‹จํžˆ ํ™•์žฅํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.

3. ๊ฐ€๋ณ€์ธ์ž

๊ฐ€๋ณ€์ธ์ž๋ž€, ์ด๋ฆ„ ๊ทธ๋Œ€๋กœ ๊ธธ์ด๊ฐ€ ๋ณ€ํ•  ์ˆ˜ ์žˆ๋Š” argument๋ฅผ ๋งํ•ฉ๋‹ˆ๋‹ค.
์ž„์˜์˜ ํ•จ์ˆ˜์— ์ธ์ž๋กœ ๋ช‡๊ฐœ์˜ ๋ฐ์ดํ„ฐ๊ฐ€ ๋“ค์–ด์˜ฌ์ง€ ๋ชจ๋ฅด๊ฒŒ ๋˜๋Š” ๊ฒฝ์šฐ์— ์‚ฌ์šฉํ•˜๋ฉด ํŽธ๋ฆฌํ•ฉ๋‹ˆ๋‹ค.
์ด๋•Œ ์—ฌ๋Ÿฌ api๋‚˜ ์ž˜ ์งœ์—ฌ์ง„ ์ฝ”๋“œ๋ฅผ ๊ตฌ๊ฒฝํ•˜๋‹ค๋ณด๋ฉด ํ•จ์ˆ˜์—ย *args๋‚˜ย **kwargs๋ผ๊ณ  ๋˜์žˆ๋Š” ํ‘œํ˜„๋“ค์„ ๋งŽ์ด ๋ณผ ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.
์ด๊ฒŒ ๋ฐ”๋กœ ๊ฐ€๋ณ€์ธ์ž๋ฅผ ์‚ฌ์šฉํ•˜๊ฒ ๋‹ค๋Š” ์˜๋ฏธ์ž…๋‹ˆ๋‹ค. ํ•œ๊ฐœ์™€ ๋‘๊ฐœ์˜ ์ฐจ์ด๋Š” positional๊ณผ keyward ์ธ์ž์˜ ์ฐจ์ด์ž…๋‹ˆ๋‹ค.
์ด๋ฆ„๋งŒ ๋“ค์–ด์„œ๋Š” ๋‚ฏ์„ค ์ˆ˜ ์žˆ์ง€๋งŒ, ์‚ฌ์‹ค ์ด๋ฏธ ์‚ฌ์šฉํ•˜๊ณ  ์žˆ์„์ง€๋„ ๋ชจ๋ฆ…๋‹ˆ๋‹ค. ๊ฐ๊ฐ์€ ์•„๋ž˜์™€ ๊ฐ™์Šต๋‹ˆ๋‹ค.
def function(a, b = None): ...
Python
๋ณต์‚ฌ
์—ฌ๊ธฐ์„œ a๋Š”ย positional arguments, b๋Š”ย keyword arguments๋ผ๊ณ  ์นญํ•ฉ๋‹ˆ๋‹ค. ๋ชจ๋‘ ์•„์‹œ๋‹ค์‹œํ”ผ a๋Š” ๊ฐ’์ด ์—†๋Š” ๊ฒฝ์šฐ error๊ฐ€ ๋œจ๊ฒŒ ๋˜๋ฉฐ, b๋Š” default๊ฐ’์œผ๋กœ None๊ฐ’์„ ์ฃผ๊ฒŒ ๋˜์ฃ .
์•„๋ž˜ ์˜ˆ์ œ์ฒ˜๋Ÿผ args๋Š” tuple ๋˜๋Š” list, kwargs๋Š” dict์— ์ €์žฅ๋˜์–ด ์ถœ๋ ฅ๋˜๋Š” ๊ฒƒ์„ ๋ณผ ์ˆ˜ ์žˆ์œผ๋ฉฐ, ๋™์‹œ์— ์‚ฌ์šฉํ•  ์ˆ˜๋„ ์žˆ์Šต๋‹ˆ๋‹ค.
def args_function(*args): print(args) def kwargs_function(**kwargs): print(kwargs) args_function('a', 'b') # ('a', 'b') kwargs_function(a = 100, b = 200) # {'a':100, 'b':200}
Python
๋ณต์‚ฌ

4. Unpacking

์•Œ๊ณ ๋ฆฌ์ฆ˜์„ ์งœ๋‹ค๋ณด๋ฉด ๊ฒฐ๊ณผ๋ถ€๋ถ„์„ ์ถœ๋ ฅํ•  ๋•Œ, for-loop๋ฅผ ์ด์šฉํ•˜์—ฌ list๋ฅผ ์ˆœํšŒํ•˜๋ฉฐ ์ถœ๋ ฅํ•˜๋Š” ๊ฒฝ์šฐ๊ฐ€ ์žˆ์Šต๋‹ˆ๋‹ค.
# list unpacking test = [1, 2, 3, 4] print(*test) # 1 2 3 4 # tuple unpacking test = (5, 6, 7, 8) print(*test) # 5 6 7 8
Python
๋ณต์‚ฌ
์ด๋ ‡๊ฒŒ ์‚ฌ์šฉํ•˜๋ฉด ์ฝ”๋“œ ๊ธธ์ด๋„ ์ค„๊ณ  ํŽธ๋ฆฌํ•˜์ฃ ?
๋‹ค์Œ์€ ๊ฐ ๋ณ€์ˆ˜ ์ค‘ ํ•˜๋‚˜์— ๊ฐ€๋ณ€์ ์œผ๋กœ ํ• ๋‹นํ•˜๊ณ  ์‹ถ์€ ๊ฒฝ์šฐ์ž…๋‹ˆ๋‹ค.
๋‹ค์Œ๊ณผ ๊ฐ™์ด ์‚ฌ์šฉํ•  ์ˆ˜๋„ ์žˆ์Šต๋‹ˆ๋‹ค.
test = [1, 2, 3, 4, 5] *a, b = test print(a, b) # [1, 2, 3, 4], 5 a, *b, c = test print(a, b, c) # 1, [2, 3, 4], 5
Python
๋ณต์‚ฌ