본문 바로가기

TIL/Python

[Python]Decorator @을 이용한 함수내 함수

함수를 다른 함수내 인자로 사용하는 여러 방법이 있다.

 

1. 일급객체 취급

def add(n1,n2) :
    return n1 + n2 
    
def subtract(n1,n2) :
    return n1 - n2 

def multiply(n1,n2) :
    return n1 * n2 

def devided(n1,n2) :
    return n1 / n2

함수를 일급 객체로 취급하여 함수 안에 함수를 쓸 수 있다.

def calc(calc_func, n1, n2) :
    return calc_fuc(n1, n2)
calc(multiply, 3, 6) // return 18

2. 중첩함수

def out_func() :
    print("Hello")
    
    def nested_func():
        print("the world!")

out_funct() 안에서 nested_func 은 존재하나 외부에서는 존재하지 않는다.

 

위와 같은 out_func() 을 실행하면 안에 있는 nested_func은  함수가 정의만 되었지 실행되지는 않는다.

out_func() // "Hello"

같이 실행하기 위해서는

def out_func() :
    print("Hello")
    
    def nested_func():
        print("the world!")
    
    nested_func()
    
out_func()
"Hello"
"the world!"

3. 함수의 결과를 다른 함수로 반환 하기

def out_func() :
    print("Hello")
    
    def nested_func():
        print("the world!")
    
    return nested_func

이때 중요한 것은 return 함수에  소괄호()를 없애는 것!

some_func = out_func() // "Hello"
some_func() // "the world!"

4. 데코레이터 @

def func1(func2) :
	##원래 함수에 함수 추가
    def wrapper_func () :
        func2()
    return wrapper_func
some_func1 = func1() //원래 함수 실행
some_func1() //추가 함수 func2 실행

위와 같이  3번처럼 함수에 함수를 설정하는 것을 간단히 @을 이용할 수 있다.  

@func1
def some_func():
	print("this is me!")


some_func() // func2() = some_func()
// func1() 실행후 
// "this is me!"

예시 

def hello(function1) :
	print("Welcome! This is")
    
	def brand():
        time.sleep(1)
        function1()
        
    return brand

fun1을 위와 같은 예시로 들고

@hello
def bread():
	print("Bread! the delicious and good favor!")
    
def fruits():
	print("Fruits! the fresh and sweetie!")
    
@hello    
def vegi():
	pirnt("Vegi! the healthy and fresh!")

bread()
fruites()
vegi()

결과

"Welcome! This is" //1초후
"Bread! the delicious and good favor!"

"Fruits! the fresh and sweetie!" // @을 사용하지 않았으므로

"Welcome! This is" //1초후
"Vegi! the healthy and fresh!"

fruits()도 "welcome~" 후 1초후에 실행되기 원한다면 위와 같이도 사용할 수 있다.

some_func = hello(fruits)
some_func()

//"Welcome! this is"
//1초후
//"Fruits, -"