๐Ÿ“ˆํŒŒ์ด์ฌ ์‹ฌํ™”(callable,*args **kwargs)

๐Ÿ”’ํŒŒ์ด์ฌ ์‹ฌํ™”(callable,*args **kwargs)

Callable

  • ๋กœ๋˜ ๋ฒˆํ˜ธ๋ฅผ ์ถœ๋ ฅํ•ด์ฃผ๋Š” ํด๋ž˜์Šค๋ฅผ ๋งŒ๋“ค์—ˆ๋‹ค.
import random 

class LottoGame:
    def __init__(self):
        self._balls = [n for n in range(1,46)]

    def pick(self):
        random.shuffle(self._balls)
        return sorted([random.choice(self._balls) for n in range(6)])
  • ๊ฐ์ฒด๋ฅผ ์ƒ์„ฑํ•ด์ค€๋‹ค. game = LottoGame()

  • ์‹คํ–‰ ํ™•์ธ

print(game.pick())  # [9, 10, 35, 38, 44, 44]
print(game())  #  TypeError: 'LottoGame' object is not callable
  • ๊ฐ์ฒด๋ฅผ ๋‹ด์€ ๋ณ€์ˆ˜์— pick()๋ฅผ ํ˜ธ์ถœ ํ•˜๋ฉด ๋˜์ง€๋งŒ ๋ณ€์ˆ˜์— () ๋ฅผ ๋ถ™์—ฌ์„œ ํ˜ธ์ถœ์„ ํ•˜๋ฉด ์—๋Ÿฌ๊ฐ€๋‚œ๋‹ค.

  • callable()ํ•จ์ˆ˜๋ฅผ ์‚ฌ์šฉํ•˜๋ฉด ๋ถ€๋ฅผ ์ˆ˜ ์žˆ๋Š”์ง€ ์—†๋Š”์ง€ ์•Œ๋ ค์ค€๋‹ค.

print(callable(str), callable(list), callable(3.14), callable(game))
# True True False False 
  • 3.14 ๊ฐ™์€ ์ˆซ์ž์™€ ์œ„์—์„œ ์ •์˜ํ•œ game ๊ฐ™์€ ๋ณ€์ˆ˜ ๊ฐ์ฒด๋Š” ํ˜ธ์ถœํ•  ์ˆ˜ ์—†๋‹ค.
  • ์ด๊ฒƒ์„ ํ˜ธ์ถœ์ด ๊ฐ€๋Šฅํ•˜๊ฒŒ ํ•˜๋Š” ๋ฐฉ๋ฒ•์ด ์žˆ๋Š”๋ฐ ....
class LottoGame:
    def __init__(self):
        self._balls = [n for n in range(1,46)]

    def pick(self):
        random.shuffle(self._balls)
        return sorted([random.choice(self._balls) for n in range(6)])

    def __call__(self):
        return self.pick()
  • def __call__(self):call๋ฉ”์†Œ๋“œ๋ฅผ ์˜ค๋ฒ„๋ผ์ด๋”ฉ ํ•˜๋ฉด ๊ฐ€๋Šฅํ•˜๋‹ค
print(callable(game))  # True
print(game()) # [3, 11, 12, 14, 32, 36]
  • callableํ•จ์ˆ˜๋ฅผ ํ†ตํ•ด game์„ ์ฐ์–ด๋ณด๋ฉด True๊ฐ€ ๋‚˜์˜ค๊ณ 
  • ํด๋ž˜์Šค๋ฅผ ๋‹ด์€ ๊ฐ์ฒด game์„ ํ˜ธ์ถœํ•ด๋„ ๊ฐ€๋Šฅํ•˜๋‹ค

๋‹ค์–‘ํ•œ ๋งค๊ฐœ๋ณ€์ˆ˜ ์ž…๋ ฅ(*args, **kwargs)

  • ๋งค๊ฐœ๋ณ€์ˆ˜๋ฅผ ์ž…๋ ฅํ•˜๋Š” ๋ถ€๋ถ„์ด ์ดํ•ด๊ฐ€์•ˆ๊ฐ€ ์ž์„ธํ•œ ์˜ˆ๋ฅผ ๋“ค์–ด๋ณด๊ฒ ๋‹ค.
def args_test(name, *contents, point=None, **attrs):
    return '<args_test> -> ({}) ({}) ({}) ({})'.format(name, contents, point, attrs)

1. ์ธ์ž 1๊ฐœ๋งŒ ์คฌ์„ ๋•Œ

print(args_test('test1'))
# (test1) (()) (None) ({})

2. ์ธ์ž๋ฅผ 2๊ฐœ ์คฌ์„ ๋•Œ

  • name์— test1์ด ๋“ค์–ด๊ฐ„๋‹ค. 2๋ฒˆ์งธ๋Š” ํŠœํ”Œํ˜•ํƒœ์— ๋น„๊ณ  3๋ฒˆ๋–„๋Š” point๋ฅผ ํ• ๋‹น์„ ์•ˆํ–ˆ๊ธฐ ๋•Œ๋ฌธ์— None์ด๊ณ  4๋ฒˆ์งธ๋Š” dict ํ˜•ํƒœ์— ๋น„์–ด์žˆ๋‹ค.
print(args_test('test1', 'test2'))
# (test1) (('test2',)) (None) ({})
  • name ์— test1์ด ๋“ค์–ด๊ฐ€๊ณ  test2๋Š” ํŠœํ”Œ ํ˜•ํƒœ๋กœ ๋“ค์–ด๊ฐ„๋‹ค. ์ดํ•˜ ๋™์ผ

3. ์ธ์ž 3๊ฐœ, dict 1๊ฐœ

print(args_test('test1','test2', 'test3', id='admin'))
# (test1) (('test2', 'test3')) (None) ({'id': 'admin'})
  • name์— test1 2๋ฒˆ์งธ ํ•ญ๋ชฉ์— ํŠœํ”Œ๋กœ test2, test3๊ฐ€ ๋“ค์–ด๊ฐ€๊ณ  3๋ฒˆ์งธ๋Š” ๋™์ผํ•˜๊ณ  4๋ฒˆ์งธ์— ๋“œ๋””์–ด dictํ˜•ํƒœ๋กœ id:admin์ด ๋“ค์–ด๊ฐ”๋‹ค.

4. + ์ง€์ •๊ฐ’

print(args_test('test1','test2', 'test3', id='admin', point=7))
# (test1) (('test2', 'test3')) (7) ({'id': 'admin'})
  • point=7 ๊ฐ’์„ ์ง€์ •ํ–ˆ๋”๋‹ˆ 3๋ฒˆ์งธ ํ•ญ๋ชฉ์— 7์ด ์ƒ๊ฒผ๋‹ค.

์ด์ œ ์žฅ๊ณ  ๊ฐœ๋ฐœํ•  ๋•Œ ํ•จ์ˆ˜์— *args **kwargs ์ž˜ ์ดํ•ดํ•˜๋„๋ก ํ•˜์ž

์ข‹์€ ์›นํŽ˜์ด์ง€ ์ฆ๊ฒจ์ฐพ๊ธฐ