Python

파이썬 일급 객체 (First-Class)

cclass 2021. 3. 5. 00:00

# 일급 객체

다른 객체들에 일반적으로 적용 가능한 연산을 모두 지원하는 객체를 일급 객체라고 한다.

일급 객체는 객체 지향 프로그래밍(OOP) 중에서 파이썬을 포함한 몇몇 프로그래밍 언어에서 발견할 수 있는 개념이다.

 

파이썬의 모든 것은 객체인데 그렇기 때문에 함수 또한 객체이며 일급 객체이고 일급 함수라고 부른다.


일급 객체란 다음의 특징을 모두 충족하는 객체를 말한다
  • 변수에 할당 할 수 있다.
  • 다른 함수를 인자로 전달받을 수 있다.
  • 다른 함수의 결과로서 리턴될 수 있다.

 

1. 변수에 할당

def print_hello(name):
    print("hello~ {}".format(name))


# 변수에 할당
var_func = print_hello
print(var_func, print_hello)
# >>> <function factorial at 0x101377160> <function factorial at 0x101377160>

var_func('python')
# >>> hello~ python
print_hello('swift')
# >>> hello~ swift

 

2. 다른 함수를 인자로 전달 받기

def print_hello():
    print('hello~')


def exec_func(func):
    print(type(func), callable(func))
    # <class 'function'> True
    return func()


exec_func(print_hello)
# >>> hello~

 

3. 함수의 결과로 리턴

def get_print_hello_func():

    def print_hello(name):
        print("hello~ {}".format(name))

    return print_hello


var_func = get_print_hello_func()

print(type(var_func))
# >>> <class 'function'>
print(var_func)
# >>> <function get_print_hello_func.<locals>.print_hello at 0x10b097d30>
var_func('python')
# >>> hello~ python