Develop Story/python

First class function

꿈꾸는만학도 2023. 10. 31. 10:46
1. definition

It means a function that can be passed as an argument to another function, returned as a result of another function, or assigned to a variable or stored in a data structure.

 함수 자체를 인자 (argument) 로써 다른 함수에 전달하거나 다른 함수의 결과값으로 리턴 할수도 있고, 함수를 변수에 할당하거나 데이터 구조안에 저장할 수 있는 함수를 뜻한다.

 

  1. assign to a variable

def add(digit):
    return digit + digit


def minus(digit):
    return 10 - digit


def multiple(digit):
    return digit * digit


def divide(digit):
    return 20 / digit


def condition(function, digit_list):
    result = list()
    for digit in digit_list:
        result.append(function(digit))
    print(result)


if __name__ == '__main__':
    int_list = [1, 2, 3, 4, 5]
    condition(add, int_list)
    condition(minus, int_list)
    condition(multiple, int_list)
    condition(divide, int_list)

 

2. return as a result of another function

def login_info(message):
    msg = message

    def msg_info():
        print("[현재]", msg)

    return msg_info


if __name__ == '__main__':
    user = login_info('user1 login')

    user()

3. application

def html_creator(tag):
    def text_wrapper(msg):
        print('<{0}>{1}</{0}>'.format(tag, msg))

    return text_wrapper


if __name__ == '__main__':
    h1_html_creator = html_creator('h1')
    print(h1_html_creator)

    h1_html_creator('h1 태그는 타이틀을 표시하는 태그입니다.')

    h1_html_creator = html_creator('p')
    h1_html_creator('p 태그는 문단을 표시하는 태그입니다.')

 

 

4. practice

def list_creator(tag):
    def list_wrapper(msg):
        print('{0} {1}'.format(tag, msg))

    return list_wrapper


if __name__ == '__main__':
    list_1 = list_creator('-')

    list_1('목차')
    list_2 = list_creator('*')
    list_2('기호')
    list_3 = list_creator('+')
    list_3('하이')