동산로의 블로그
First class citizens(objects) feat. python 본문
First-class object란 값처럼 자유롭게 다룰 수 있는 객체를 말합니다. python에서는 함수도 first-class object입니다. 함수를 변수에 할당, 함수에 인자로 전달, 함수의 반환값으로 반환, 자료 구조에 저장 할 수 있습니다.
함수를 변수에 assign 할 수도 있고
def greet(name):
return f"Hello, {name}!"
say_hello = greet
print(say_hello("Alice"))
함수를 인자(arguments)으로 넘겨줄 수 있다.
def shout(text):
return text.upper()
def speak(func, message):
return func(message)
print(speak(shout, "hello"))
함수를 함수로 반환 가능하다.
def get_multiplier(factor):
def multiply(x):
return x * factor
return multiply
times3 = get_multiplier(3)
print(times3(10))
데이터 구조에 함수를 저장 가능.
def add(x,y): return x+y
def subtract(x, y): return x-y
operations = {
'add': add,
'subtract' : subtract
}
print(operations['add](10,5))