-
[Python] - First class functions개발/Python 2022. 7. 28. 17:55
1. First class Obejct
Define
1. You can store them in Variable , Data Structure(list,dictionary .. )
2. You can pass the function as a parameter to another function
3. You can return the function from a function.2. First class functions
Python support first class functions, it means function is instance of Object.
First class functions includes First class Object properties.
First class functions's feature
2-1) functions are Object
# 1. Functions are Objects def change_lower(text): return text.lower() test = change_lower print(test('HELLO World')) > hello world
2-2) Functions can be passed as arguements to other functions
# 2. Functions can be passed as arguements to other functions def change_lower(text): return text.lower() def change_upper(text): return text.upper() def change_word(func,text): return func(text) print( change_word(change_lower,text) ) > hello world print( change_word(change_upper,text) ) > HELLO WORLD
2-3) Functions can return another functions
how get log object have text?
- log_message function called "closure function"
- closure function remeber local variable after origin function return
# 3. Functions can return another functions def logging(text): def log_message(): print( 'log_msg : {}'.format(text)) return log_message log = logging('test') print(log) > <function logging.<locals>.log_message at 0x000001EBFE366EF0> log() > log_msg : test
Why we use first class function
def logging(risk): def wrap_msg(msg): print('{0}-{1} '.format(risk,msg)) return wrap_msg risk_4 = logging('4') risk_4('404') > 4-404 risk_4('400') 4-400 risk_2 = logging(2) risk_2('200') > 2-200
'개발 > Python' 카테고리의 다른 글
[Python] - Decorator (0) 2022.09.02 [Python] - Closure (0) 2022.07.28 [Python] - Generator (0) 2022.07.28 [Python] - Call by Object reference & Call by sharing (0) 2022.07.28 [Python] - Counter (0) 2022.07.27