Notice
Recent Posts
Recent Comments
Link
«   2025/06   »
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30
Archives
Today
Total
관리 메뉴

동산로의 블로그

First class citizens(objects) feat. python 본문

카테고리 없음

First class citizens(objects) feat. python

동산로 2025. 4. 15. 13:57

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))