<aside> 💡 프로그래밍에서 일급 객체란 ‘값’처럼 다뤄질 수 있는 요소를 말합니다. 파이썬과 같은 언어에서는 함수도 일급 객체입니다.
</aside>
def add(x, y):
return x + y
def subt(x, y):
return x - y
def mult(x, y):
return x * y
def div(x, y):
return x / y
1. 변수에 값으로 할당될 수 있음
# 💡 다른 변수에 할당
arith_1 = add
add_3_4 = arith_1(3, 4)
pass
2. 함수의 반환값이 될 수 있음
# 💡 다른 함수를 반환하는 함수
def get_arith_func(get_add=True):
return add if get_add else subt
arith_1 = get_arith_func(True)
arith_2 = get_arith_func(False)
num_1 = arith_1(5, 3)
num_2 = arith_2(5, 3)
pass
3. 함수의 매개변수로 전달될 수 있음
# 💡 다른 함수를 매개변수로 받는 함수
def calculate(arith, x, y):
return arith(x, y)
calc_1 = calculate(add, 3, 4)
calc_2 = calculate(mult, 3, 4)
4. 컬랙션 등의 요소로 포함될 수 있음
# 💡 함수들을 담은 리스트
arith_list = [add, subt, mult, div]
arith_3_4_results = [arith(3, 4) for arith in arith_list]