Python - Function, Parameter, Arguments(positional, variable length, variable length keyword)

full_accel·2020년 11월 20일
0

파이썬의 함수와 매개변수에 대한 간단한 포스팅입니다.
아래의 사항들에 대해서 알아봅니다.

  • Function
    • 함수
  • Parameter
    • 매개변수 / 형식인수 -> 함수가 값을 받기위해 사용하는 변수
  • Argument
    • 인수 / 실인수 -> 실제로 함수에 전달되는 값
    • positional arguments
    • keywrod arguments
    • variable arguments
    • variable length keyword arguments
    • Argument들을 사용하는 순서

함수(function)

function:
1. 명사 (사람사물의) 기능
2. 명사 행사, 의식
3. 동사 (제대로) 기능하다(작용하다) (=operate)

  • 함수(function)는 무언가 기능을 하는 코드의 묶음이다.
  • ex) 투자 자문 기능을 해주는 파이썬 함수를 구현해 보자.
from random import randrange as revelation_of_god


def god_bless():
    round = 6
    lottery = []
    while round != 0:
        lottery.append(revelation_of_god(1, 46))
        round -= 1
    print(f"Let the believer have light! \n {lottery}")


god_bless()

# 실행 결과
# Let the believer have light! 
# [30, 40, 4, 39, 17, 35]

Parameter

parameter: 매개 변수

매개 변수: 1. 수학 두 개 이상의 변수 사이의 함수 관계를 간접적으로 표시할 때 사용하는 변수.

  • 사전적인 정의를 보고 Parameter를 이해하기는 어려운 것 같다.
    • 오히려 방해되는 것 같다.
  • 파이썬과 대부분의 언어에서 Parameter(매개변수)는 함수에 값을 넘겨주기 위해서 사용되는 변수이다.

Parameter와 Argument

  • 투자 자문을 받을 때 친절하게 사용자의 이름을 언급해주면 왠지 모르게 투자 수익률이 더 좋을 것 같다.
  • parameter와 arugument로 투자 자문 함수를 고도화 해보자.

parameter(매개변수)와 argument(인수) 예제

from random import randrange as revelation_of_god


# your_name은 parameter(매개변수)
def god_bless_you(your_name):
    round = 6
    lottery = []
    while round != 0:
        lottery.append(revelation_of_god(1, 46))
        round -= 1
    print(f"Let {your_name} have light! \n {lottery}")
    return lottery


# my_name("Homer-Jay-Simpson")은 argument(인수)
my_name = "Homer-Jay-Simpson"
god_bless_you(my_name)

# 실행 결과
# Let Homer-Jay-Simpson have light! 
# [26, 45, 44, 31, 36, 17]

  • 신께서 친히 이름을 불러주니 투자 결과가 더 좋을 것 같다.

Parameter와 Argument 설명

간단한 수식에 비유해서 parameter(매개변수)와 argument(인수)를 이해해 보자.

  • X = a + 2라는 수식에 대해서 a = 5를 넣으면 X 값은 7이 된다.
    • X = a + 2는 함수로 볼 수 있고
    • a = 5에서
      • a는 parameter(매개변수 / 형식인수)
        • 수식에서 숫자를 받기 위해 형식적으로 존재하는 문자(형식인수)
      • 5는 argument(인수 / 실인수)
        • 실제로 수식에 넘겨지는 값(실인수)
    • 추가적으로 X의 값인 7은 함수의 리턴값에 대응된다.

파이썬의 특수한 Arguments

  • 파이썬은 함수에 parameter 값을 넘겨주는 다양한 방식들을 제공한다.
    • Positional Arguments(위치 인수)
    • Keyword Arguments(키워드 인수)
    • variable length arguments(가변 인수)
    • variable length keyword arguments(가변 키워드 인수)

Positional Argument

  • 위에서 제대로 설명하지 않고 어물쩍 넘어갔지만, 사실 위에서 설명한 Argument는 positional argument(위치 인수)이다.
  • positional argument(위치 인수)는 순서대로 넣어줘야 함수가 정상적으로 동작한다.

Keyword Arguments

  • 아래의 예제 코드는 매개변수를 넘겨주는 순서가 꼬여서 신에게 축복을 받아야 하는데 오히려 신에게 축복을 해버렸다. 이래 가지고는 제대로된 투자 결과를 기대할 수 없다.
  • Keyword Arguments를 이용하면 이런 사단을 예방할 수 있다.

parameter 입력에 문제가 있는 예제

from random import randrange as revelation_of_god


def god_bless_you(your_name, your_god):
    round = 6
    lottery = []
    while round != 0:
        lottery.append(revelation_of_god(1, 46))
        round -= 1
    print(f"Behold! {your_god} says \n"
          f"Let {your_name} have light! \n"
          f"{lottery}")


my_name = "Homer-Jay-Simpson"
my_god = "Zeus"

god_bless_you(my_god, my_name)

# 실행 결과
# Behold! Homer-Jay-Simpson says 
# Let Zeus have light! 
# [10, 43, 8, 6, 26, 40]

parameter 전달 순서가 꼬여서 결과가 이상해졌다.

  • 위의 예제는 parameter가 두 개이지만 그 갯수가 아주 많은 함수도 얼마든지 만들어 질 수 있다.
  • 그런 경우 parameter를 맞는 위치에 잘 넘겨주는 것도 공수가 들어간다.
  • 더욱이 위의 코드와 같은 문제가 있는 경우 분명 문제가 있음(휴먼에러!)에도 실행 자체는 잘 되기 때문에 테스트 중 발견하기가 어렵다.
  • 이러한 문제들을 keyword argument를 이용하여 해결해 보자.

Keyword Arguments 예제

from random import randrange as revelation_of_god


def god_bless_you(your_name, your_god):
    round = 6
    lottery = []
    while round != 0:
        lottery.append(revelation_of_god(1, 46))
        round -= 1
    print(f"Behold! {your_god} says \n"
          f"Let {your_name} have light! \n"
          f"{lottery}")


my_name = "Homer-Jay-Simpson"
my_god = "Zeus"

god_bless_you(your_god=my_god, your_name=my_name)

# 실행 결과
# Behold! Zeus says 
# Let Homer-Jay-Simpson have light! 
# [28, 15, 36, 27, 9, 44]

Keyword Arguments 설명

  • keyword arguments는 함수를 호출할 때 parameter(매개변수 / 형식인수)에 argument(인수 / 실인수)를 순차적으로 넘겨주는 대신에 각각의 parameter(매개변수 / 형식인수)에 argument(인수 / 실인수)를 지정해서 넘겨준다.
  • 이 때에 넘겨주는 순서가 함수의 정의된 순서와 달라도 정상적으로 잘 동작한다.

variable length arguments(가변 인수) / *args

가변 인수 예제

  • 한 번에 한 명만 투자 자문을 받는 것은 비효율적인 것 같다.
  • 가변 인수(*args)로 한 번에 여러 개의 값을 넘겨 투자자문 함수를 고도화시켜 보자.
  • 아래의 코드 실행 결과로 부녀가 한 번에 투자자문을 받았다.
from random import randrange as revelation_of_god


def god_bless_you(your_god, *args):
    for foolish_human_being in args:
        round = 6
        lottery = []
        while round != 0:
            lottery.append(revelation_of_god(1, 46))
            round -= 1
        print(f"Behold! \n"
              f"Let {foolish_human_being} have light! \n"
              f"{lottery} \n")


god_bless_you(my_god, "Homer-Jay-Simpson", "Lisa-Simpson")

# 실행 결과
# Behold!
# Let Homer-Jay-Simpson have light! 
# [43, 27, 33, 41, 1, 24] 

# Behold! 
# Let Lisa-Simpson have light! 
# [3, 23, 43, 16, 27, 19] 

가변 인수 설명

  • 매개변수 앞에 *를 붙여주면 입력값이 전부 튜플로 만들어져 함수 내부에서 사용된다.
  • 위의 예제에서 매개변수 *args는 ("Homer-Jay-Simpson", "Lisa-Simpson")인 튜플이 된다.
  • *args 대신 다른 이름으로 매개변수를 정할 수도 있다.
  • 하지만 파이썬에서는 관습적으로 *args를 사용한다.

variable length keyword arguments(가변 키워드 인수) / **kwargs

가변 키워드 인수 예제

  • 고오급 투자 정보를 모든 고객에게 동일하게 제공하는 것은 수익 극대화 측면에서 바람직하지 않은 것 같다.
  • 가변 키워드 인수(**kwargs)를 이용해서 돈을 더 많이낸 VIP 고객에게만 고오급 투자정보를 알려주고, 급이 낮으면 적게 알려주도록 투자 자문 함수를 고도화 해보자.
from random import randrange as revelation_of_god


def god_bless_you(your_god, **kwargs):
    for fool, grade in kwargs.items():
        if grade == "VIP":
            round = 6
            lottery = []
            while round != 0:
                lottery.append(revelation_of_god(1, 46))
                round -= 1
            print(f"Behold! {your_god} Says! \n"
                  f"Let {fool} have light! \n"
                  f"{lottery} \n")
        else:
            round = 5
            lottery = []
            while round != 0:
                lottery.append(revelation_of_god(1, 46))
                round -= 1
            print(f"Behold! {your_god} Says! \n"
                  f"Let {fool} have some little light! \n"
                  f"{lottery} \n")


your_god = "Zeus"
god_bless_you(your_god, Homer="VIP", Moe="not VIP")

# 실행 결과
# VIP는 모든 정보를 받고 VIP가 아니면 불완전한 정보를 받는다.
# Behold! Zeus Says! 
# Let Homer have light! 
# [16, 28, 25, 17, 31, 45] 

# Behold! Zeus Says! 
# Let Moe have some little light! 
# [3, 37, 40, 31, 23] 

가변 키워드 인수 예제 설명

  • 매개변수 앞에 **를 붙여주면 입력값이 전부 딕셔너리로 만들어져 함수 내부에서 사용된다.
  • 위의 예제에서 매개변수 **kwargs는 {"Homer": "VIP", "Moe": "not VIP"}인 딕셔너리가 된다.
  • **kwargs 대신 다른 이름으로 매개변수를 정할 수도 있다.
  • 하지만 파이썬에서는 관습적으로 **kwargs를 사용한다.

Arguments를 사용하는 순서

  • *args는 일반 매개변수보다 뒤에 위치해야 한다.
    • 그래야 어디까지를 *args에 담을지 알 수 있다.
  • 비슷한 이유로 **kwargs*args 다음에 와야 한다.
profile
스스로 배운 것이 오래 간다.

0개의 댓글